<?php

namespace app\admin\controller;

use app\api\model\ConfigAlipay;
use app\api\model\ConfigPersonal;
use app\api\model\Labels;
use app\api\model\Privatechat;
use app\api\model\LabelsUser;
use app\api\model\Reg;
use app\api\model\User;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use app\api\model\OrderCommon;
use app\api\model\PrivatechatGreet;
use think\Db;
use think\Request;
use think\Session;
use app\api\model\Task;
use app\api\model\PrivatechatDeleTask;
use think\Cache;
use app\api\model\ConfigSystem as Config;
use app\api\model\UserPunish;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Vectorface\Whip\Whip;
use app\service\UserIntimate;
use app\service\UserLevel;
use app\service\RedisQueue;

class Member extends Common
{
    public $userLevels = ['普通会员','超级会员','运营商','合伙人'];
    public function adminlog()
    {
        $where = [];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $where['city'] = ['like', $admin['city'] . '%'];
        }

        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('admin_logs t1')
            ->field('t1.*, t2.name')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                $item['day'] = 0;
                if (strpos($item['content'], '封禁账号至') !== false) {
                    $datetime = explode(' ', explode('封禁账号至',$item['content'])[1])[0];

                    // 计算时间差
                    $banTimestamp = strtotime($datetime);
                    $currentTimestamp = strtotime($item['time']);

                    // 获取天数差
                    $timeDifference = $banTimestamp - $currentTimestamp;
                    $daysDifference = ceil($timeDifference / (60 * 60 * 24));
                    $item['day'] = $daysDifference;
                }
                return $item;
            });

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //会员管理
    public function index()
    {

        // 避免锁行导致出错
        try{
            // 处理账号到期解冻
            $bannedids = Db::name('user')
                ->where(['is_banned' => 1, 'banned_end_time' => ['elt', date('Y-m-d H:i:s')]])
                ->column('id');
            if(sizeof($bannedids)){
                Db::name('user')->where(['id'=>['in', $bannedids]])->update(['is_banned' => 0, 'banned_end_time' => null]);
                // $readRules = Db::name('config_personal')->where(['user_id'=>['in',$bannedids], 'is_read_rule'=>1])->column('user_id');
                // Db::name('user')->where(['id'=>['in', $readRules]])->update(['is_banned' => 0, 'banned_end_time' => null]);
            }
        } catch (Exception $e) {

        }

        $memberIndexCacheTime = 600;
        $dangerTags = Db::name('danger_tags')->cache(60)->column('id,content');

        //$where = ['proxy' => ['neq', 1]];
        $where = ['id' => ['gt', 0]];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $where['city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');
        if ($type == 1) {
            $where['vip_end_datetime'] = ['egt', date('Y-m-d H:i:s')];
        } else if ($type == 2) {
            $where['is_identity_authentication'] = '2';
            $where['sex'] = "女";
        }  else if ($type == 3) {//今日注册数
			// 方案1：直接使用时间范围筛选（更可靠）
			$todayStart = date('Y-m-d 00:00:00');
			$where['register_datetime'] = ['egt', $todayStart];
			// 可选：如果需要兼容ID筛选，同时使用两个条件
			$firstId = Db::name('user')
				->where(['register_datetime' => ['egt', $todayStart]])
				->order('id asc') // 确保按ID升序获取第一个用户
				->value('id');
			$firstId = $firstId ?: 9999999999;
			// 使用AND条件组合两个筛选（更严格） 单纯根据id不对 已注销的用户的恢复会更新注册时间
			$where['id'] = ['egt', $firstId];
		}

        $xuni = input('xuni/d');
        if ($xuni) {
            $xuni_table = $xuni - 1;
            $where['role'] = $xuni_table;
        }

        $sex = input('sex');
        if ($sex) {
            $where['reg'] = 1;
            $where['sex'] = $sex;
        }

        $is_online = input('is_online');
        if ($is_online) {
            $where['reg'] = 1;
            $where['is_online'] = $is_online;
        }
    
        $recommend = input('recommend');
        if ($recommend) {
            $where['is_recommend'] = $recommend;
        }

        $is_contact = input('is_contact');
        if ($is_contact !== null) {
            $where['is_contact'] = $is_contact;
        }

        $reward = input('reward');
        if ($reward) {
            $order = 'shouyi_xuni desc, shouyi desc';
        } else {
            $order = 'sort desc, id desc';
        }
    
        $time = input('time');
        if ($time !== null) {
            if ($time) {
                $order = 'id desc';
                $time = 0;
            } else {
                $order = 'id asc';
                $time = 1;
            }
        }
    
        $balance = input('balance');
        if ($balance !== null) {
            if ($balance) {
                $order = 'volley desc, id desc';
                $balance = 0;
            } else {
                $order = 'volley asc, id desc';
                $balance = 1;
            }
        }
    
        $score = input('score');
        if ($score !== null) {
            if ($score) {
                $order = 'score desc, id desc';
                $score = 0;
            } else {
                $order = 'score asc, id desc';
                $score = 1;
            }
        }
    
        $logintime = input('logintime');
        if ($logintime !== null) {
            $order = 'last_login_datetime asc, id desc';
            $logintime = 1;
        }
    
        $shouyi = input('shouyi');
        if ($shouyi !== null) {
            $order = 'shouyi desc, id desc';
            $shouyi = 1;
        }


        // 是否查询关联账号
        $uniaccount = false;
        // 设备号
        $uni_userids_a = [];
        $uni_userids_g = [];
        $uni_userids_h = [];
        // 支付宝
        $uni_userids_b = [];
        $uni_userids_e = [];
        $uni_userids_i = [];
        // 收款人名称
        $uni_userids_c = [];
        $uni_userids_f = [];
        // 手机号
        $uni_userids_d = [];
        // 后台手动关联
        $uni_userids_k = [];
        // 充值用户标识
        $uni_userids_j = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if ($search_type == 'uniaccount' && $search_name) {
                $uniaccount = true;
                // 根据id查用户数据
                $uinfo = Db::name('user')->where(['id' => $search_name])->find();
                if($uinfo['device_id']){
                    $uni_userids_a = Db::name('recycle_user')->where(['data' => ['like', '%'.$uinfo['device_id'].'%']])->cache($memberIndexCacheTime)->column('user_id');
                    $uni_userids_g = Db::name('user')->where(['device_id' => $uinfo['device_id']])->cache($memberIndexCacheTime)->column('id');
                }
                if($uinfo['zhifucount']){
                    $uni_userids_b = Db::name('recycle_user')->where(['data' => ['like', '%"zhifucount":"'.$uinfo['zhifucount'].'"%']])->cache($memberIndexCacheTime)->column('user_id');
                    $uni_userids_e = Db::name('user')->where(['zhifucount' => $uinfo['zhifucount']])->cache($memberIndexCacheTime)->column('id');
                }
                if($uinfo['zhifuname'] && mb_strlen($uinfo['zhifuname'])>1){
                    $uni_userids_c = Db::name('recycle_user')->where(['data' => ['like', '%"zhifuname":"'.$uinfo['zhifuname'].'"%']])->cache($memberIndexCacheTime)->column('user_id');
                    $uni_userids_f = Db::name('user')->where(['zhifuname' => $uinfo['zhifuname']])->cache($memberIndexCacheTime)->column('id');
                }
                if($uinfo['phone']){
                    $uni_userids_d = Db::name('recycle_user')->where(['phone' => $uinfo['phone']])->cache($memberIndexCacheTime)->column('user_id');
                }

                $historyData = Db::name('user_repeat_check')->find($search_name);

                if ($uinfo['device_id']) {
                    $historyData['device_ids'] = $historyData['device_ids']?$historyData['device_ids'].','.$uinfo['device_id']:$uinfo['device_id'];
                }

                if(isset($historyData['device_ids']) && $historyData['device_ids']){
                    $tmp = explode(',', $historyData['device_ids']);
                    $where_1 = [];
                    $whereUDevs = [];
                    foreach ($tmp as $key => $value) {
                        if (strlen($value) < 5) continue;
                        $whereUDevs[] = $value;
                        $where_1[] = "device_ids like '%".$value."%'";
                    }
                    if (sizeof($where_1)) {
                        // $uni_userids_h = Db::name('user_repeat_check')->master()->where(implode(' or ', $where_1))->cache($memberIndexCacheTime)->column('user_id');
                        $uni_userids_h = Db::name('user_device_records')->master()->where(['device_id'=>['in',$whereUDevs]])->cache($memberIndexCacheTime)->group('user_id')->column('user_id');
                        $uni_userids_h_2 = Db::name('user')->where(['device_id'=>['in',$whereUDevs]])->column('id');
                        $uni_userids_h = array_merge($uni_userids_h, $uni_userids_h_2);
                    }
                }
                if(isset($historyData['pay_ids']) && $historyData['pay_ids']){
                    $tmp = explode(',', $historyData['pay_ids']);
                    $where_3 = [];
                    foreach ($tmp as $key => $value) {
                        if (strlen($value) < 5) continue;
                        $where_3[] = "pay_ids like '%".$value."%'";
                    }
                    if (sizeof($where_3)) {
                        $uni_userids_j = Db::name('user_repeat_check')->master()->where(implode(' or ', $where_3))->cache($memberIndexCacheTime)->column('user_id');
                    }
                }
                if(isset($historyData['zhifucounts']) && $historyData['zhifucounts']){
                    $tmp = explode(',', $historyData['zhifucounts']);
                    $where_2 = [];
                    foreach ($tmp as $key => $value) {
                        $where_2[] = "zhifucounts like '%".$value."%'";
                    }
                    if (sizeof($where_2)) {
                        $uni_userids_i = Db::name('user_repeat_check')->master()->where(implode(' or ', $where_2))->cache($memberIndexCacheTime)->column('user_id');
                    }
                }
                if(isset($historyData['custom']) && $historyData['custom']){
                    $uni_userids_k = explode(',', $historyData['custom']);
                }


                $where['id'] = ['in', array_unique(array_merge($uni_userids_a, $uni_userids_b, $uni_userids_c , $uni_userids_d, $uni_userids_e, $uni_userids_f, $uni_userids_g, $uni_userids_h, $uni_userids_i, $uni_userids_k, $uni_userids_j))];
            } else if (in_array($search_type, ['id', 'yqr'])) {
                $where[$search_type] = $search_name;
            } else if ($search_type == 'device_id' && $search_name) {
                $recycle_userids = Db::name('recycle_user')->where(['data' => ['like', '%'.$search_name.'%']])->cache($memberIndexCacheTime)->column('user_id');
                $unzhuxiao_userids = Db::name('user')->where(['device_id' => $search_name])->cache($memberIndexCacheTime)->column('id');
                $where['id'] = ['in', array_merge($recycle_userids,$unzhuxiao_userids)];
            } else if ($search_type == 'phone' && $search_name) {
                $recycle_userids = Db::name('recycle_user')->where(['phone' => ['like', '%'.$search_name.'%']])->cache($memberIndexCacheTime)->column('user_id');
                $unzhuxiao_userids = Db::name('user')->where(['phone' => ['like', '%'.$search_name.'%']])->cache($memberIndexCacheTime)->column('id');
                $where['id'] = ['in', array_merge($recycle_userids,$unzhuxiao_userids)];
            } else if ($search_type == 'cluster') {
                $ids = Db::name('cluster_user')->where(['cluster_id' => $search_name])->column('user_id');

                if ($ids) {
                    $where['id'] = ['in', $ids];
                } else {
                    $where['id'] = 0;
                }
            } else if ($search_type == 'flag_supervise') {
                $ids = Db::name('flag_supervise')->where(['flag_id' => $search_name])->column('user_id');

                if ($ids) {
                    $where['id'] = ['in', $ids];
                } else {
                    $where['id'] = 0;
                }
            } else if ($search_type == 'ids') {
                $where['id'] = ['in', $search_name];
            } else if ($search_type == 'shouyi') {
                $where['reg'] = 1;
                $where['shouyi'] = ['>=', $search_name];
            } else if ($search_type == 'consume') {
                $where['reg'] = 1;
                $consumes = Db::name('user_data')->where(['consume'=>['>=', $search_name]])->column('user_id');
                $where['id'] = ['in', $consumes];
            } else if ($search_type == 'idcard') {
                $consumes = Db::name('user_certification')->where(['types'=>1, 'data'=>$search_name])->column('user_id');
                $where['id'] = ['in', $consumes];
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $proxy = input('proxy');
        if ($proxy) {

            $channel = input('channel');
            switch ($channel) {
                case 1:
                    $where['yqr'] = $proxy;
                    break;
                case 2:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->group('user_id')->cache($memberIndexCacheTime)->column('user_id');
                        if ($uids) {
                            $where['id'] = ['in', $uids];
                        } else {
                            $where['id'] = 0;
                        }
                    } else {
                        $where['id'] = 0;
                    }
                    break;
                case 3:
                    $where['yqr'] = $proxy;
                    $where['register_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime(date('Ymd')))];
                    break;
                case 4:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->whereTime('update_time', 'd')->order('id desc')->group('user_id')->cache($memberIndexCacheTime)->column('user_id');
                    } else {
                        $uids = [];
                    }
                    if ($uids) {
                        $where['id'] = ['in', $uids];
                    } else {
                        $where['id'] = 0;
                    }
                    break;
            }
        }

        $datemin = input('datemin', '');
        $datemax = input('datemax', '');
        $this->assign('datemin', $datemin);
        $this->assign('datemax', $datemax);
        $datetimekey = input('time_type');
        if (in_array($datetimekey, ['last_login_time', 'delete_time'])) {
            $datemin = $datemin?strtotime($datemin):'';
            $datemax = $datemax?strtotime($datemax):'';
        }
        if ($datemin) {
            $where['reg'] = 1;
            if ($datemax) {
                $where[$datetimekey] = ['between', [$datemin, $datemax]];
            } else {
                $where[$datetimekey] = ['>=', $datemin];
            }
        } else if ($datemax) {
            $where['reg'] = 1;
            $where[$datetimekey] = ['<=', $datemax];
        }

        $zhuxiao = input('zhuxiao', 0);
        if ($zhuxiao) {
            $where['delete_time'] = ['>',0];
        }
        $this->assign('zhuxiao', $zhuxiao);

        $is_banned = input('is_banned', 0);
        if ($is_banned) {
            $where['is_banned'] = ['>',0];
        }
        $this->assign('is_banned', $is_banned);

        $notparent = input('notparent', 0);
        if ($notparent) {
            $where['reg'] = 1;
            $where['delete_time'] = 0;
            $where['yqr'] = ['=',''];
        }
        $this->assign('notparent', $notparent);
        
        $realnameauth = input('realnameauth', 0);
        if ($realnameauth) {
            $where['realname_auth'] = ['<>',2];
        }
        $this->assign('realnameauth', $realnameauth);

        $quality = input('quality');
        if ($quality || $quality === '0') {
            $where['quality'] = $quality;
            $where['reg'] = 1;
            $this->assign('quality', $quality);
        }

        $data = Db::name('user')
                ->master(true)
                ->where($where)
                ->order($order)
                ->field('id,yqr,head_portrait,name,delete_time,sex,phone,volley,score,shouyi,shouyi_xuni,yqm,noble_grade,noble_time,is_identity_authentication,register_datetime,device_id,zhifucount,last_login_datetime,city,is_recommend,sort,is_contact,is_banned,zhifuname,danger_tags,quality,realname_auth,reg,authcode,jiaoyou_lv,porno_lv,level,level_lock,volley_gift,beans')
                ->paginate(_getCachePages(), false, ['query' => request()->param()])
                ->each(function($item, $key) use ($memberIndexCacheTime, $uniaccount, $uni_userids_a, $uni_userids_b, $uni_userids_c, $uni_userids_d, $uni_userids_e, $uni_userids_f, $uni_userids_g, $uni_userids_h, $uni_userids_i, $uni_userids_k, $search_name, $dangerTags, $uni_userids_j){
                    return $item;
            // 输出关联项
            if($uniaccount){
                $item['uniobject'] = [];
                if($item['id'] == $search_name){
                    $item['uniobject'] = '当前账号';
                }else{
                    if(in_array($item['id'], $uni_userids_a) || in_array($item['id'], $uni_userids_g) || in_array($item['id'], $uni_userids_h)){
                        $item['uniobject'][] = '设备号';
                    }
                    if(in_array($item['id'], $uni_userids_b) || in_array($item['id'], $uni_userids_e) || in_array($item['id'], $uni_userids_i)){
                        $item['uniobject'][] = '收款支付宝';
                    }
                    if(in_array($item['id'], $uni_userids_c) || in_array($item['id'], $uni_userids_f)){
                        $item['uniobject'][] = '收款人名称';
                    }
                    if(in_array($item['id'], $uni_userids_d)){
                        $item['uniobject'][] = '手机号';
                    }
                    if(in_array($item['id'], $uni_userids_j)){
                        $item['uniobject'][] = '支付标识';
                    }
                    if(in_array($item['id'], $uni_userids_k)){
                        $item['uniobject'][] = '手动关联';
                    }
                    $item['uniobject'] = implode(',', $item['uniobject']);
                }
            }


            $userData = Db::name('user_data')->where(['user_id' => $item['id']])->cache(120)->find();

            $item['consume_sum'] = $userData ? $userData['consume'] : 0;
            //$item['income_sum'] = $userData ? $userData['income'] : 0;
            $item['income_sum'] = $item['shouyi'];
            $item['device_account_count'] = 1;




            $uni_userids_in_a = [];
            $uni_userids_in_b = [];
            $uni_userids_in_c = [];
            $uni_userids_in_d = [];

            $where_1 = [];
            $where_2 = [];
            if($item['device_id']){
                $where_1[] = "data like '%".$item['device_id']."%'";
                $where_2[] = "device_id = '".$item['device_id']."'";
            }
            if($item['zhifucount']){
                $where_1[] = "data like '%zhifucount\":\"".$item['zhifucount']."\"%'";
                $where_2[] = "zhifucount = '".$item['zhifucount']."'";
            }
            if($item['zhifuname']){
                $where_1[] = "data like '%zhifuname\":\"".$item['zhifuname']."\"%'";
                $where_2[] = "zhifuname = '".$item['zhifuname']."'";
            }
            if($item['phone']){
                $where_1[] = "phone = '".$item['phone']."'";
            }

            if (sizeof($where_1)) {
                $uni_userids_in_a = Db::name('recycle_user')->where(implode(' or ', $where_1))->cache($memberIndexCacheTime)->column('user_id');
            }
            if (sizeof($where_2)) {
                $uni_userids_in_b = Db::name('user')->where(implode(' or ', $where_2))->cache($memberIndexCacheTime)->column('id');
            }


            $historyData = Db::name('user_repeat_check')->cache(120)->find($item['id']);
            if ($item['device_id']) {
                $historyData['device_ids'] = $historyData['device_ids']?$historyData['device_ids'].','.$item['device_id']:$item['device_id'];
            }
            $where_3 = [];
            $where_devices = [];
            if(isset($historyData['device_ids']) && $historyData['device_ids']){
                $tmp = explode(',', $historyData['device_ids']);
                foreach ($tmp as $key => $value) {
                    if (strlen($value) < 5) continue;
                    $where_devices[] = $value;
                    // $where_3[] = "device_ids like '%".$value."%'";
                }
            }
            if(isset($historyData['pay_ids']) && $historyData['pay_ids']){
                $tmp = explode(',', $historyData['pay_ids']);
                foreach ($tmp as $key => $value) {
                    $where_3[] = "pay_ids like '%".$value."%'";
                }
            }
            if(isset($historyData['zhifucounts']) && $historyData['zhifucounts']){
                $tmp = explode(',', $historyData['zhifucounts']);
                foreach ($tmp as $key => $value) {
                    $where_3[] = "zhifucounts like '%".$value."%'";
                }
            }
            if (sizeof($where_3)) {
                $uni_userids_in_c = Db::name('user_repeat_check')->master()->where(implode(' or ', $where_3))->cache($memberIndexCacheTime)->column('user_id');
            }
            if (sizeof($where_devices)) {
                $tmparr = Db::name('user_device_records')->master()->where(['device_id'=>['in',$where_devices]])->cache($memberIndexCacheTime)->group('user_id')->column('user_id');
                $tmparrUser = Db::name('user')->where(['device_id'=>['in', $where_devices]])->cache($memberIndexCacheTime)->column('id');
                $uni_userids_in_c = array_merge($tmparr, $tmparrUser, $uni_userids_in_c);
            }
            if(isset($historyData['custom']) && $historyData['custom']){
                $uni_userids_in_d = explode(',', $historyData['custom']);
            }

            $item['device_account_count'] = sizeof(array_unique(array_merge($uni_userids_in_a, $uni_userids_in_b, $uni_userids_in_c , $uni_userids_in_d, [$item['id']])));
            $item['device_account_count'] = $item['device_account_count'] ? $item['device_account_count'] : 1;

            // if($item['device_id']){
            //     $recycle_uids = Db::name('recycle_user')->where(['data' => ['like', '%'.$item['device_id'].'%']])->column('user_id');
            //     $inline_uids = Db::name('user')->where(['device_id'=>$item['device_id']])->column('id');
            //     $all_uids = array_merge($recycle_uids, $inline_uids);
            //     $item['device_account_count'] = sizeof($all_uids);
            // }


            $item['topup_sum'] = 0;
            // if($item['device_account_count'] > 1){
            //     $item['withdraw_sum'] = 0;
            //     $withdrawdata = [];
            //     foreach ($all_uids as $uid) {
            //         // $userData = Db::name('user_data')->where(['user_id' => $item['id']])->find();
            //         // $item['topup_sum'] += $userData ? $userData['topup'] : 0;
            //         $wdata = Db::name('withdraw')->where(['userid'=>$uid, 'state'=>['in', [0,1]]])->find();
            //         if($wdata){
            //             $wdata = json_decode($wdata['data'], true);
            //             if(!in_array($wdata['account'], $withdrawdata)){
            //                 $withdrawdata[] = $wdata['account'];
            //             }
            //         }
            //     }
            //     foreach ($withdrawdata as $wdataitem) {
            //         $item['withdraw_sum'] += Db::name('withdraw')->where(['data' => ['like', '%'.$wdataitem.'%'], 'state' => ['in', [0,1]]])->sum('money');
            //     }
            // }else{
                $item['withdraw_sum'] = Db::name('withdraw')->where(['userid' => $item['id'], 'state' => ['in', [0,1]]])->cache(10)->sum('money');
            // }
            $item['topup_sum'] = $userData ? $userData['topup'] : 0;
            $danger_tags = $item['danger_tags'] ? explode(',', $item['danger_tags']) : [];
            $userdangertag = [];
            foreach ($danger_tags as $dv) {
                $userdangertag[] = $dangerTags[$dv];
            }
            $item['danger_tags_value'] = implode(' ', $userdangertag);
            return $item;
        });

        $dataList = $data->toArray();
        $dataList = $dataList['data'];

        $userDatas = Db::name('user_data')->where(['user_id' => ['in', array_column($dataList, 'id')]])->cache(120)->column('*','user_id');
        $historyDatas = Db::name('user_repeat_check')->where(['user_id' => ['in', array_column($dataList, 'id')]])->cache(120)->column('*','user_id');
        $withdraws = Db::name('withdraw')->where(['userid' => ['in', array_column($dataList, 'id')], 'state' => ['in', [0,1]]])->cache(10)->fetchSql(false)->group('userid')->column('sum(money) money', 'userid');

        $wallet_frozen = db('wallet_frozen')->where(['user_id'=>['in', array_column($dataList, 'id')]])->column('value', 'user_id');
        $withdraw_limit = db('withdraw_limit')->where(['user_id'=>['in', array_column($dataList, 'id')]])->column('user_id');
        $limit_chat = db('limit_chat')->where(['user_id'=>['in', array_column($dataList, 'id')]])->column('user_id');
        $admin_kefu = db('admin')->where(['type'=>2,'name'=>['in', array_column($dataList, 'phone')]])->column('name');

        foreach ($dataList as $key => &$item) {
            $item['level_text'] = $this->userLevels[$item['level']] ?? '异常';
            if ($this->adminInfo['type'] !=1){
                $item['phone'] = substr_replace($item['phone'],'****',3,4);
            }

            // 输出关联项
            if($uniaccount){
                $item['uniobject'] = [];
                if($item['id'] == $search_name){
                    $item['uniobject'] = '当前账号';
                }else{
                    if(in_array($item['id'], $uni_userids_a) || in_array($item['id'], $uni_userids_g) || in_array($item['id'], $uni_userids_h)){
                        $item['uniobject'][] = '设备号';
                    }
                    if(in_array($item['id'], $uni_userids_b) || in_array($item['id'], $uni_userids_e) || in_array($item['id'], $uni_userids_i)){
                        $item['uniobject'][] = '收款支付宝';
                    }
                    if(in_array($item['id'], $uni_userids_c) || in_array($item['id'], $uni_userids_f)){
                        $item['uniobject'][] = '收款人名称';
                    }
                    if(in_array($item['id'], $uni_userids_d)){
                        $item['uniobject'][] = '手机号';
                    }
                    if(in_array($item['id'], $uni_userids_j)){
                        $item['uniobject'][] = '支付标识';
                    }
                    if(in_array($item['id'], $uni_userids_k)){
                        $item['uniobject'][] = '手动关联';
                    }
                    $item['uniobject'] = implode(',', $item['uniobject']);
                }
            }


            $userData = $userDatas[$item['id']] ?? false;

            $item['consume_sum'] = $userData ? $userData['consume'] : 0;
            //$item['income_sum'] = $userData ? $userData['income'] : 0;
            $item['income_sum'] = $item['shouyi'];
            $item['device_account_count'] = 1;




            $uni_userids_in_a = [];
            $uni_userids_in_b = [];
            $uni_userids_in_c = [];
            $uni_userids_in_d = [];

            $where_1 = [];
            $where_2 = [];
            if($item['device_id']){
                $where_1[] = "data like '%".$item['device_id']."%'";
                $where_2[] = "device_id = '".$item['device_id']."'";
            }
            if($item['zhifucount']){
                $where_1[] = "data like '%zhifucount\":\"".$item['zhifucount']."\"%'";
                $where_2[] = "zhifucount = '".$item['zhifucount']."'";
            }
            if($item['zhifuname']){
                $where_1[] = "data like '%zhifuname\":\"".$item['zhifuname']."\"%'";
                $where_2[] = "zhifuname = '".$item['zhifuname']."'";
            }
            if($item['phone']){
                $where_1[] = "phone = '".$item['phone']."'";
            }

            if (sizeof($where_1)) {
                $uni_userids_in_a = Db::name('recycle_user')->where(implode(' or ', $where_1))->cache($memberIndexCacheTime)->column('user_id');
            }
            if (sizeof($where_2)) {
                $uni_userids_in_b = Db::name('user')->where(implode(' or ', $where_2))->cache($memberIndexCacheTime)->column('id');
            }


            $historyData = $historyDatas[$item['id']]??false;
            if ($item['device_id']) {
                $historyData['device_ids'] = $historyData['device_ids']?$historyData['device_ids'].','.$item['device_id']:$item['device_id'];
            }
            $where_3 = [];
            $where_devices = [];
            if(isset($historyData['device_ids']) && $historyData['device_ids']){
                $tmp = explode(',', $historyData['device_ids']);
                foreach ($tmp as $key => $value) {
                    if (strlen($value) < 5) continue;
                    $where_devices[] = $value;
                    // $where_3[] = "device_ids like '%".$value."%'";
                }
            }
            if(isset($historyData['pay_ids']) && $historyData['pay_ids']){
                $tmp = explode(',', $historyData['pay_ids']);
                foreach ($tmp as $key => $value) {
                    $where_3[] = "pay_ids like '%".$value."%'";
                }
            }
            if(isset($historyData['zhifucounts']) && $historyData['zhifucounts']){
                $tmp = explode(',', $historyData['zhifucounts']);
                foreach ($tmp as $key => $value) {
                    $where_3[] = "zhifucounts like '%".$value."%'";
                }
            }
            if (sizeof($where_3)) {
                $uni_userids_in_c = Db::name('user_repeat_check')->master()->where(implode(' or ', $where_3))->cache($memberIndexCacheTime)->column('user_id');
            }
            if (sizeof($where_devices)) {
                $tmparr = Db::name('user_device_records')->master()->where(['device_id'=>['in',$where_devices]])->cache($memberIndexCacheTime)->group('user_id')->column('user_id');
                $tmparrUser = Db::name('user')->where(['device_id'=>['in', $where_devices]])->cache($memberIndexCacheTime)->column('id');
                $uni_userids_in_c = array_merge($tmparr, $tmparrUser, $uni_userids_in_c);
            }
            if(isset($historyData['custom']) && $historyData['custom']){
                $uni_userids_in_d = explode(',', $historyData['custom']);
            }

            $item['device_account_count'] = sizeof(array_unique(array_merge($uni_userids_in_a, $uni_userids_in_b, $uni_userids_in_c , $uni_userids_in_d, [$item['id']])));
            $item['device_account_count'] = $item['device_account_count'] ? $item['device_account_count'] : 1;


            $item['topup_sum'] = 0;
            $item['withdraw_sum'] = $withdraws[$item['id']]??0;
            $item['topup_sum'] = $userData ? $userData['topup'] : 0;

            $item['wallet_frozen'] = $wallet_frozen[$item['id']] ?? 0;
            $item['withdraw_limit'] = in_array($item['id'], $withdraw_limit);
            $item['limit_chat'] = in_array($item['id'], $limit_chat);
            $item['admin_kefu'] = in_array($item['phone'], $admin_kefu);

            $danger_tags = $item['danger_tags'] ? explode(',', $item['danger_tags']) : [];
            $userdangertag = [];
            foreach ($danger_tags as $dv) {
                $userdangertag[] = $dangerTags[$dv];
            }
            $item['danger_tags_value'] = implode(' ', $userdangertag);
        }

        $count = Db::name('user')->where($where)->cache(60)->count();
        $sum = Db::name('user')->cache(60)->count();

        $vip = Db::name('grade_noble')->order('sort desc, id asc')->cache($memberIndexCacheTime)->column('grade, id, name');
        $this->assign('vip', $vip);

        $car = Db::name('car')->where(['is_hidden' => 0])->cache($memberIndexCacheTime)->column('id, name, description');
        $this->assign('car', $car);

        $this->assign('dangerTags', $dangerTags);
        $this->assign('type', $type);
        $this->assign('xuni', $xuni);
        $this->assign('sex', $sex);
        $this->assign('is_online', $is_online);
        $this->assign('recommend', $recommend);
        $this->assign('is_contact', $is_contact);
        $this->assign('reward', $reward);
        $this->assign('count', $count);
        $this->assign('sum', $sum);
        
        $this->assign('time', $time);
        $this->assign('balance', $balance);
        $this->assign('score', $score);
        $this->assign('logintime', $logintime);
        $this->assign('shouyi', $shouyi);

        $this->assign('admin', $admin);
        $this->assign('uniaccount', $uniaccount);

        $this->assign('data', $dataList);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //会员管理
    public function indexs()
    {
        $dangerTags = Db::name('danger_tags')->column('id,content');

        //$where = ['proxy' => ['neq', 1]];
        $where = ['reg'=>1];

        $type = input('type');
        if ($type == 1) {
            $where['vip_end_datetime'] = ['egt', date('Y-m-d H:i:s')];
        } else if ($type == 2) {
            $where['is_identity_authentication'] = '2';
            $where['sex'] = "女";
        } else if ($type == 3) {
            $where['register_datetime'] = ['egt', date('Y-m-d')];
        }

        $xuni = input('xuni/d');
        if ($xuni) {
            $xuni_table = $xuni - 1;
            $where['role'] = $xuni_table;
        }

        $sex = input('sex');
        if ($sex) {
            $where['reg'] = 1;
            $where['sex'] = $sex;
        }

        $is_online = input('is_online');
        if ($is_online) {
            $where['reg'] = 1;
            $where['is_online'] = $is_online;
        }
    
        $recommend = input('recommend');
        if ($recommend) {
            $where['is_recommend'] = $recommend;
        }

        $is_contact = input('is_contact');
        if ($is_contact !== null) {
            $where['is_contact'] = $is_contact;
        }

        $reward = input('reward');
        if ($reward) {
            $order = 'shouyi_xuni desc, shouyi desc';
        } else {
            $order = 'sort desc, id desc';
        }
    
        $time = input('time');
        if ($time !== null) {
            if ($time) {
                $order = 'id desc';
                $time = 0;
            } else {
                $order = 'id asc';
                $time = 1;
            }
        }
    
        $balance = input('balance');
        if ($balance !== null) {
            if ($balance) {
                $order = 'volley desc, id desc';
                $balance = 0;
            } else {
                $order = 'volley asc, id desc';
                $balance = 1;
            }
        }
    
        $score = input('score');
        if ($score !== null) {
            if ($score) {
                $order = 'score desc, id desc';
                $score = 0;
            } else {
                $order = 'score asc, id desc';
                $score = 1;
            }
        }
    
        $logintime = input('logintime');
        if ($logintime !== null) {
            $order = 'last_login_datetime asc, id desc';
            $logintime = 1;
        }


        // 是否查询关联账号
        $uniaccount = false;
        // 设备号
        $uni_userids_a = [];
        $uni_userids_g = [];
        $uni_userids_h = [];
        // 支付宝
        $uni_userids_b = [];
        $uni_userids_e = [];
        $uni_userids_i = [];
        // 收款人名称
        $uni_userids_c = [];
        $uni_userids_f = [];
        // 手机号
        $uni_userids_d = [];
        // 后台手动关联
        $uni_userids_k = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if ($search_type == 'uniaccount' && $search_name) {
                $uniaccount = true;
                // 根据id查用户数据
                $uinfo = Db::name('user')->where(['id' => $search_name])->find();
                if($uinfo['device_id']){
                    $uni_userids_a = Db::name('recycle_user')->where(['data' => ['like', '%'.$uinfo['device_id'].'%']])->column('user_id');
                    $uni_userids_g = Db::name('user')->where(['device_id' => $uinfo['device_id']])->column('id');
                }
                if($uinfo['zhifucount']){
                    $uni_userids_b = Db::name('recycle_user')->where(['data' => ['like', '%"zhifucount":"'.$uinfo['zhifucount'].'"%']])->column('user_id');
                    $uni_userids_e = Db::name('user')->where(['zhifucount' => $uinfo['zhifucount']])->column('id');
                }
                if($uinfo['zhifuname'] && mb_strlen($uinfo['zhifuname'])>1){
                    $uni_userids_c = Db::name('recycle_user')->where(['data' => ['like', '%"zhifuname":"'.$uinfo['zhifuname'].'"%']])->column('user_id');
                    $uni_userids_f = Db::name('user')->where(['zhifuname' => $uinfo['zhifuname']])->column('id');
                }
                if($uinfo['phone']){
                    $uni_userids_d = Db::name('recycle_user')->where(['phone' => $uinfo['phone']])->column('user_id');
                }

                $historyData = Db::name('user_repeat_check')->find($search_name);
                if($historyData){
                    if($historyData['device_ids']){
                        $tmp = explode(',', $historyData['device_ids']);
                        $where_1 = [];
                        $whereUDevs = [];
                        foreach ($tmp as $key => $value) {
                            if (strlen($value) < 5) continue;
                            $whereUDevs[] = $value;
                            $where_1[] = "device_ids like '%".$value."%'";
                        }
                        if (sizeof($where_1)) {
                            // $uni_userids_h = Db::name('user_repeat_check')->master()->where(implode(' or ', $where_1))->column('user_id');
                            $uni_userids_h = Db::name('user_device_records')->master()->where(['device_id'=>['in',$whereUDevs]])->cache($memberIndexCacheTime)->group('user_id')->column('user_id');
                            $uni_userids_h_2 = Db::name('user')->where(['device_id'=>['in',$whereUDevs]])->column('id');
                            $uni_userids_h = array_merge($uni_userids_h, $uni_userids_h_2);
                        }
                    }
                    if($historyData['zhifucounts']){
                        $tmp = explode(',', $historyData['zhifucounts']);
                        $where_2 = [];
                        foreach ($tmp as $key => $value) {
                            $where_2[] = "zhifucounts like '%".$value."%'";
                        }
                        if (sizeof($where_2)) {
                            $uni_userids_i = Db::name('user_repeat_check')->master()->where(implode(' or ', $where_2))->column('user_id');
                        }
                    }
                    if($historyData['custom']){
                        $uni_userids_k = explode(',', $historyData['custom']);
                    }
                }


                $where['id'] = ['in', array_unique(array_merge($uni_userids_a, $uni_userids_b, $uni_userids_c , $uni_userids_d, $uni_userids_e, $uni_userids_f, $uni_userids_g, $uni_userids_h, $uni_userids_i, $uni_userids_k))];
            } else if (in_array($search_type, ['id', 'yqr'])) {
                $where[$search_type] = $search_name;
            } else if ($search_type == 'device_id' && $search_name) {
                $recycle_userids = Db::name('recycle_user')->where(['data' => ['like', '%'.$search_name.'%']])->column('user_id');
                $unzhuxiao_userids = Db::name('user')->where(['device_id' => $search_name])->column('id');
                $where['id'] = ['in', array_merge($recycle_userids,$unzhuxiao_userids)];
            } else if ($search_type == 'phone' && $search_name) {
                $recycle_userids = Db::name('recycle_user')->where(['phone' => ['like', '%'.$search_name.'%']])->column('user_id');
                $unzhuxiao_userids = Db::name('user')->where(['phone' => ['like', '%'.$search_name.'%']])->column('id');
                $where['id'] = ['in', array_merge($recycle_userids,$unzhuxiao_userids)];
            } else if ($search_type == 'cluster') {
                $ids = Db::name('cluster_user')->where(['cluster_id' => $search_name])->column('user_id');

                if ($ids) {
                    $where['id'] = ['in', $ids];
                } else {
                    $where['id'] = 0;
                }
            } else if ($search_type == 'flag_supervise') {
                $ids = Db::name('flag_supervise')->where(['flag_id' => $search_name])->column('user_id');

                if ($ids) {
                    $where['id'] = ['in', $ids];
                } else {
                    $where['id'] = 0;
                }
            } else if ($search_type == 'ids') {
                $where['id'] = ['in', $search_name];
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $proxy = input('proxy');
        if ($proxy) {

            $channel = input('channel');
            switch ($channel) {
                case 1:
                    $where['yqr'] = $proxy;
                    break;
                case 2:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->group('user_id')->column('user_id');
                        if ($uids) {
                            $where['id'] = ['in', $uids];
                        } else {
                            $where['id'] = 0;
                        }
                    } else {
                        $where['id'] = 0;
                    }
                    break;
                case 3:
                    $where['yqr'] = $proxy;
                    $where['register_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime(date('Ymd')))];
                    break;
                case 4:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->whereTime('update_time', 'd')->order('id desc')->group('user_id')->column('user_id');
                    } else {
                        $uids = [];
                    }
                    if ($uids) {
                        $where['id'] = ['in', $uids];
                    } else {
                        $where['id'] = 0;
                    }
                    break;
            }
        }

        $datemin = input('datemin', '');
        $datemax = input('datemax', '');
        $this->assign('datemin', $datemin);
        $this->assign('datemax', $datemax);
        $datetimekey = input('time_type');
        if ($datetimekey == 'last_login_time') {
            $datemin = $datemin?strtotime($datemin):'';
            $datemax = $datemax?strtotime($datemax):'';
        }
        if ($datemin) {
            $where['reg'] = 1;
            if ($datemax) {
                $where[$datetimekey] = ['between', [$datemin, $datemax]];
            } else {
                $where[$datetimekey] = ['>=', $datemin];
            }
        } else if ($datemax) {
            $where['reg'] = 1;
            $where[$datetimekey] = ['<=', $datemax];
        }

        $zhuxiao = input('zhuxiao', 0);
        if ($zhuxiao) {
            $where['delete_time'] = ['>',0];
        }
        $this->assign('zhuxiao', $zhuxiao);

        $is_banned = input('is_banned', 0);
        if ($is_banned) {
            $where['is_banned'] = ['>',0];
        }
        $this->assign('is_banned', $is_banned);

        $notparent = input('notparent', 0);
        if ($notparent) {
            $where['reg'] = 1;
            $where['yqr'] = ['=',''];
        }
        $this->assign('notparent', $notparent);
        
        $realnameauth = input('realnameauth', 0);
        if ($realnameauth) {
            $where['realname_auth'] = ['<>',2];
        }
        $this->assign('realnameauth', $realnameauth);

        $quality = input('quality');
        if ($quality || $quality === '0') {
            $where['quality'] = $quality;
            $where['reg'] = 1;
            $this->assign('quality', $quality);
        }

        $user_repeat_check = Db::name('user_repeat_check')->where(['account_count'=>['>', 1]])->column('account_count', 'user_id');

        if (!isset($where['id'])) {
            $where['id'] = ['in', array_keys($user_repeat_check)];
        }

        $data = Db::name('user')
                ->where($where)
                ->order($order)
                ->field('id,yqr,head_100,name,delete_time,sex,phone,volley,score,shouyi,shouyi_xuni,yqm,noble_grade,noble_time,is_identity_authentication,register_datetime,device_id,zhifucount,last_login_datetime,city,is_recommend,sort,is_contact,is_banned,zhifuname,danger_tags,quality,realname_auth,reg,authcode')
                ->paginate(_getCachePages(), false, ['query' => request()->param()])
                ->each(function($item, $key) use ($uniaccount, $uni_userids_a, $uni_userids_b, $uni_userids_c, $uni_userids_d, $uni_userids_e, $uni_userids_f, $uni_userids_g, $uni_userids_h, $uni_userids_i, $uni_userids_k, $search_name, $dangerTags, $user_repeat_check){

            // 输出关联项
            if($uniaccount){
                $item['uniobject'] = [];
                if($item['id'] == $search_name){
                    $item['uniobject'] = '当前账号';
                }else{
                    if(in_array($item['id'], $uni_userids_a) || in_array($item['id'], $uni_userids_g) || in_array($item['id'], $uni_userids_h)){
                        $item['uniobject'][] = '设备号';
                    }
                    if(in_array($item['id'], $uni_userids_b) || in_array($item['id'], $uni_userids_e) || in_array($item['id'], $uni_userids_i)){
                        $item['uniobject'][] = '收款支付宝';
                    }
                    if(in_array($item['id'], $uni_userids_c) || in_array($item['id'], $uni_userids_f)){
                        $item['uniobject'][] = '收款人名称';
                    }
                    if(in_array($item['id'], $uni_userids_d)){
                        $item['uniobject'][] = '手机号';
                    }
                    if(in_array($item['id'], $uni_userids_k)){
                        $item['uniobject'][] = '手动关联';
                    }
                    $item['uniobject'] = implode(',', $item['uniobject']);
                }
            }


            $userData = Db::name('user_data')->where(['user_id' => $item['id']])->find();

            $item['consume_sum'] = $userData ? $userData['consume'] : 0;
            //$item['income_sum'] = $userData ? $userData['income'] : 0;
            $item['income_sum'] = $item['shouyi'];
            $item['device_account_count'] = $user_repeat_check[$item['id']] ?? Db::name('user_repeat_check')->where(['user_id'=>$item['id']])->value('account_count');
            $item['user_realname'] = Db::name('user_certification')->where(['user_id'=>$item['id'],'types'=>1, 'status'=>1])->value('data2');

            // if($item['device_id']){
            //     $recycle_uids = Db::name('recycle_user')->where(['data' => ['like', '%'.$item['device_id'].'%']])->column('user_id');
            //     $inline_uids = Db::name('user')->where(['device_id'=>$item['device_id']])->column('id');
            //     $all_uids = array_merge($recycle_uids, $inline_uids);
            //     $item['device_account_count'] = sizeof($all_uids);
            // }


            $item['topup_sum'] = 0;
            // if($item['device_account_count'] > 1){
            //     $item['withdraw_sum'] = 0;
            //     $withdrawdata = [];
            //     foreach ($all_uids as $uid) {
            //         // $userData = Db::name('user_data')->where(['user_id' => $item['id']])->find();
            //         // $item['topup_sum'] += $userData ? $userData['topup'] : 0;
            //         $wdata = Db::name('withdraw')->where(['userid'=>$uid, 'state'=>['in', [0,1]]])->find();
            //         if($wdata){
            //             $wdata = json_decode($wdata['data'], true);
            //             if(!in_array($wdata['account'], $withdrawdata)){
            //                 $withdrawdata[] = $wdata['account'];
            //             }
            //         }
            //     }
            //     foreach ($withdrawdata as $wdataitem) {
            //         $item['withdraw_sum'] += Db::name('withdraw')->where(['data' => ['like', '%'.$wdataitem.'%'], 'state' => ['in', [0,1]]])->sum('money');
            //     }
            // }else{
                $item['withdraw_sum'] = Db::name('withdraw')->where(['userid' => $item['id'], 'state' => ['in', [0,1]]])->cache(10)->sum('money');
            // }
            $item['topup_sum'] = $userData ? $userData['topup'] : 0;
            $danger_tags = $item['danger_tags'] ? explode(',', $item['danger_tags']) : [];
            $userdangertag = [];
            foreach ($danger_tags as $dv) {
                $userdangertag[] = $dangerTags[$dv];
            }
            $item['danger_tags_value'] = implode(' ', $userdangertag);
            return $item;
        });

        $count = Db::name('user')->where($where)->count();
        $sum = Db::name('user')->count();

        $vip = Db::name('grade_noble')->order('sort desc, id asc')->column('grade, id, name');
        $this->assign('vip', $vip);

        $car = Db::name('car')->where(['is_hidden' => 0])->column('id, name, description');
        $this->assign('car', $car);

        $this->assign('dangerTags', $dangerTags);
        $this->assign('type', $type);
        $this->assign('xuni', $xuni);
        $this->assign('sex', $sex);
        $this->assign('is_online', $is_online);
        $this->assign('recommend', $recommend);
        $this->assign('is_contact', $is_contact);
        $this->assign('reward', $reward);
        $this->assign('count', $count);
        $this->assign('sum', $sum);
        
        $this->assign('time', $time);
        $this->assign('balance', $balance);
        $this->assign('score', $score);
        $this->assign('logintime', $logintime);

        $this->assign('uniaccount', $uniaccount);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //会员管理
    public function indexofip()
    {

        // 避免锁行导致出错
        try{
            // 处理账号到期解冻
            $bannedids = Db::name('user')
                ->where(['is_banned' => 1, 'banned_end_time' => ['elt', date('Y-m-d H:i:s')]])
                ->column('id');
            if(sizeof($bannedids)){
                Db::name('user')->where(['id'=>['in', $bannedids]])->update(['is_banned' => 0, 'banned_end_time' => null]);
                // $readRules = Db::name('config_personal')->where(['user_id'=>['in',$bannedids], 'is_read_rule'=>1])->column('user_id');
                // Db::name('user')->where(['id'=>['in', $readRules]])->update(['is_banned' => 0, 'banned_end_time' => null]);
            }
        } catch (Exception $e) {

        }

        //$where = ['proxy' => ['neq', 1]];
        $where = ['id' => ['gt', 0]];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $where['city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');
        if ($type == 1) {
            $where['vip_end_datetime'] = ['egt', date('Y-m-d H:i:s')];
        } else if ($type == 2) {
            $where['is_identity_authentication'] = '2';
            $where['sex'] = "女";
        } else if ($type == 3) {
            $where['register_datetime'] = ['egt', date('Y-m-d')];
        }

        $xuni = input('xuni/d');
        if ($xuni) {
            $xuni_table = $xuni - 1;
            $where['role'] = $xuni_table;
        }

        $sex = input('sex');
        if ($sex) {
            $where['sex'] = $sex;
        }

        $is_online = input('is_online');
        if ($is_online) {
            $where['is_online'] = $is_online;
        }
    
        $recommend = input('recommend');
        if ($recommend) {
            $where['is_recommend'] = $recommend;
        }

        $is_contact = input('is_contact');
        if ($is_contact !== null) {
            $where['is_contact'] = $is_contact;
        }

        $reward = input('reward');
        if ($reward) {
            $order = 'shouyi_xuni desc, shouyi desc';
        } else {
            $order = 'sort desc, id desc';
        }
    
        $time = input('time');
        if ($time !== null) {
            if ($time) {
                $order = 'id desc';
                $time = 0;
            } else {
                $order = 'id asc';
                $time = 1;
            }
        }
    
        $balance = input('balance');
        if ($balance !== null) {
            if ($balance) {
                $order = 'volley desc, id desc';
                $balance = 0;
            } else {
                $order = 'volley asc, id desc';
                $balance = 1;
            }
        }
    
        $score = input('score');
        if ($score !== null) {
            if ($score) {
                $order = 'score desc, id desc';
                $score = 0;
            } else {
                $order = 'score asc, id desc';
                $score = 1;
            }
        }


        // 是否查询关联账号
        $uniaccount = false;
        // ip
        $uni_userids_j = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if ($search_type == 'uniaccount' && $search_name) {
                $uniaccount = true;
                // 根据id查用户数据
                $historyData = Db::name('user_repeat_check')->find($search_name);
                if($historyData){
                    if($historyData['ips']){
                        $tmp = explode(',', $historyData['ips']);
                        foreach ($tmp as $key => $value) {
                            $tmparr = Db::name('user_repeat_check')->master()->where(['ips' => ['like', '%'.$value.'%']])->column('user_id');
                            $uni_userids_j = array_merge($uni_userids_j, $tmparr);
                        }
                    }
                }


                $where['id'] = ['in', array_unique($uni_userids_j)];
            } else if (in_array($search_type, ['id', 'yqr'])) {
                $where[$search_type] = $search_name;
            } else if ($search_type == 'device_id' && $search_name) {
                $recycle_userids = Db::name('recycle_user')->where(['data' => ['like', '%'.$search_name.'%']])->column('user_id');
                $unzhuxiao_userids = Db::name('user')->where(['device_id' => $search_name])->column('id');
                $where['id'] = ['in', array_merge($recycle_userids,$unzhuxiao_userids)];
            } else if ($search_type == 'phone' && $search_name) {
                $recycle_userids = Db::name('recycle_user')->where(['phone' => ['like', '%'.$search_name.'%']])->column('user_id');
                $unzhuxiao_userids = Db::name('user')->where(['phone' => ['like', '%'.$search_name.'%']])->column('id');
                $where['id'] = ['in', array_merge($recycle_userids,$unzhuxiao_userids)];
            } else if ($search_type == 'cluster') {
                $ids = Db::name('cluster_user')->where(['cluster_id' => $search_name])->column('user_id');

                if ($ids) {
                    $where['id'] = ['in', $ids];
                } else {
                    $where['id'] = 0;
                }
            } else if ($search_type == 'ip') {
                $ids = Db::name('user_repeat_check')->master()->where('find_in_set("'.$search_name.'",ips)')->column('user_id');

                if ($ids) {
                    $where['id'] = ['in', $ids];
                }
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $proxy = input('proxy');
        if ($proxy) {

            $channel = input('channel');
            switch ($channel) {
                case 1:
                    $where['yqr'] = $proxy;
                    break;
                case 2:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->group('user_id')->column('user_id');
                        if ($uids) {
                            $where['id'] = ['in', $uids];
                        } else {
                            $where['id'] = 0;
                        }
                    } else {
                        $where['id'] = 0;
                    }
                    break;
                case 3:
                    $where['yqr'] = $proxy;
                    $where['register_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime(date('Ymd')))];
                    break;
                case 4:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->whereTime('update_time', 'd')->order('id desc')->group('user_id')->column('user_id');
                    } else {
                        $uids = [];
                    }
                    if ($uids) {
                        $where['id'] = ['in', $uids];
                    } else {
                        $where['id'] = 0;
                    }
                    break;
            }
        }

        $date = input('date');
        if ($date) {
            $where['register_datetime'] = ['like', '%' . $date . '%'];
        }

        $zhuxiao = input('zhuxiao', 0);
        if ($zhuxiao) {
            $where['delete_time'] = ['>',0];
        }
        $this->assign('zhuxiao', $zhuxiao);

        $notparent = input('notparent', 0);
        if ($notparent) {
            $where['yqr'] = ['=',''];
        }
        $this->assign('notparent', $notparent);

        $data = Db::name('user')->where($where)->order($order)->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function($item, $key) use ($uniaccount, $uni_userids_j, $search_name){

            // 输出关联项
            if($uniaccount){
                $item['uniobject'] = [];
                if($item['id'] == $search_name){
                    $item['uniobject'] = '当前账号';
                }else{
                    if(in_array($item['id'], $uni_userids_j)){
                        $item['uniobject'][] = 'IP';
                    }
                    $item['uniobject'] = implode(',', $item['uniobject']);
                }
            }


            $userData = Db::name('user_data')->where(['user_id' => $item['id']])->find();

            $item['consume_sum'] = $userData ? $userData['consume'] : 0;
            //$item['income_sum'] = $userData ? $userData['income'] : 0;
            $item['income_sum'] = $item['shouyi'];
            $item['device_account_count'] = 1;




            $uni_userids_in_j = [];
            $historyData = Db::name('user_repeat_check')->find($item['id']);
            if($historyData){
                if($historyData['ips']){
                    $tmp = explode(',', $historyData['ips']);
                    foreach ($tmp as $key => $value) {
                        $tmparr = Db::name('user_repeat_check')->master()->where(['ips' => ['like', '%'.$value.'%']])->column('user_id');
                        $uni_userids_in_j = array_merge($uni_userids_in_j, $tmparr);
                    }
                }
            }

            $item['device_account_count'] = sizeof(array_unique($uni_userids_in_j));
            $item['device_account_count'] = $item['device_account_count'] ? $item['device_account_count'] : 1;

            // if($item['device_id']){
            //     $recycle_uids = Db::name('recycle_user')->where(['data' => ['like', '%'.$item['device_id'].'%']])->column('user_id');
            //     $inline_uids = Db::name('user')->where(['device_id'=>$item['device_id']])->column('id');
            //     $all_uids = array_merge($recycle_uids, $inline_uids);
            //     $item['device_account_count'] = sizeof($all_uids);
            // }


            $item['topup_sum'] = 0;
            // if($item['device_account_count'] > 1){
            //     $item['withdraw_sum'] = 0;
            //     $withdrawdata = [];
            //     foreach ($all_uids as $uid) {
            //         // $userData = Db::name('user_data')->where(['user_id' => $item['id']])->find();
            //         // $item['topup_sum'] += $userData ? $userData['topup'] : 0;
            //         $wdata = Db::name('withdraw')->where(['userid'=>$uid, 'state'=>['in', [0,1]]])->find();
            //         if($wdata){
            //             $wdata = json_decode($wdata['data'], true);
            //             if(!in_array($wdata['account'], $withdrawdata)){
            //                 $withdrawdata[] = $wdata['account'];
            //             }
            //         }
            //     }
            //     foreach ($withdrawdata as $wdataitem) {
            //         $item['withdraw_sum'] += Db::name('withdraw')->where(['data' => ['like', '%'.$wdataitem.'%'], 'state' => ['in', [0,1]]])->sum('money');
            //     }
            // }else{
                $item['withdraw_sum'] = Db::name('withdraw')->where(['userid' => $item['id'], 'state' => ['in', [0,1]]])->sum('money');
            // }
            $item['topup_sum'] = $userData ? $userData['topup'] : 0;
            return $item;
        });

        $count = Db::name('user')->where($where)->count();
        $sum = Db::name('user')->count();

        $vip = Db::name('grade_noble')->order('sort desc, id asc')->column('grade, id, name');
        $this->assign('vip', $vip);

        $car = Db::name('car')->where(['is_hidden' => 0])->column('id, name, description');
        $this->assign('car', $car);

        $this->assign('type', $type);
        $this->assign('xuni', $xuni);
        $this->assign('sex', $sex);
        $this->assign('is_online', $is_online);
        $this->assign('recommend', $recommend);
        $this->assign('is_contact', $is_contact);
        $this->assign('reward', $reward);
        $this->assign('count', $count);
        $this->assign('sum', $sum);
        
        $this->assign('time', $time);
        $this->assign('balance', $balance);
        $this->assign('score', $score);

        $this->assign('admin', $admin);
        $this->assign('uniaccount', $uniaccount);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    // 添加会员
    public function add()
    {
        $id = input('id');
        $xuni = input('xuni/d');
        $admin = Session::get('admin', 'mmjtAdmin');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!isset($post['longitude']) || !$post['longitude']) {
                unset($post['longitude']);
            }

            if (!isset($post['latitude']) || !$post['latitude']) {
                unset($post['latitude']);
            }

            if (isset($post['fencheng_user']) && $post['fencheng_user']) {
                $post['fencheng_user'] = $post['fencheng_user'] / 100;
            }

            if ($xuni) {
                $userNum = $post['userNum'];
                unset($post['userNum']);
            }

            if ($post['sex'] == '男') {
                if (isset($post['dy_conditions_woman'])) {
                    unset($post['dy_conditions_woman']);
                }

                if (isset($post['dy_conditions_man'])) {
                    $post['dy_conditions'] = implode(',',$post['dy_conditions_man']);
                    unset($post['dy_conditions_man']);
                } else {
                    $post['dy_conditions'] = '';
                }
            } else {
                if (isset($post['dy_conditions_man'])) {
                    unset($post['dy_conditions_man']);
                }

                if (isset($post['dy_conditions_woman'])) {
                    $post['dy_conditions'] = implode(',',$post['dy_conditions_woman']);
                    unset($post['dy_conditions_woman']);
                } else {
                    $post['dy_conditions'] = '';
                }
            }

            if (isset($post['dy_program'])) {
                $post['dy_program'] = implode(',',$post['dy_program']);
            } else {
                $post['dy_program'] = '';
            }

            if (isset($post['good_label'])) {
                $good_label = implode(',',$post['good_label']);
                unset($post['good_label']);
            } else {
                $good_label = '';
            }

            if (isset($post['interested_label'])) {
                $interested_label = implode(',',$post['interested_label']);
                unset($post['interested_label']);
            } else {
                $interested_label = '';
            }
            if (isset($post['entertainment_child']) && $post['entertainment_child']) {
                $entertainment_child = implode(',',$post['entertainment_child']);
            } else {
                $entertainment_child = '';
            }
            $post['entertainment_child'] = $entertainment_child;

            $validate = validate('Member');

            if ($validate->check($post)) {

                if (!$id) {
                    // if ($admin['type'] != 1) {
                    //     return ['err' => '无权限'];
                    // }


                    if (!$post['password']) {
                        return ['err' => '请填写密码'];
                    }
                    $post['password'] = User::encryptPassword($post['password']);

                    if (!$post['sex']) {
                        return ['err' => '请填写性别'];
                    }

                    if (isset($post['birthday'])) {
                        $post['age'] = (time() - strtotime($post['birthday'])) / 86400 / 365;
                    } else if (isset($post['age']) && $post['age'] > 0) {
                        $post['birthday'] = date('Y-m-d', strtotime('- '. ($post['age']) . 'year') + 86400 * (rand(1, 30)));
                    }

                    if (isset($post['paypwd']) && $post['paypwd'] !== '') {
                        $post['paypwd'] = password_hash($post['paypwd'], PASSWORD_DEFAULT);
                    }

                    if (isset($post['phone']) && $post['phone']) {
                        $res = Db::name('user')->where('phone', $post['phone'])->select();
                        if ($res) {
                            return ['err' => '手机号已存在'];
                        }
                    } else {
                        $post['phone'] = null;
                    }

                    if (!$post['head_portrait'] && !$xuni) {
                        //return ['err' => '请先上传头像'];
                    } else {
                        $post['head_300'] = $post['head_portrait'];
                        $post['head_100'] = $post['head_portrait'];
                    }

                    if ($xuni) {
                        $contain = [];
                        for ($i = 0; $i < $userNum; $i++) {

                            //生成唯一邀请码
                            for ($k = 1; $k < 2; $k++) {
                                $code = code();

                                $test = Db::table('user')->where(['yqm' => $code])->select();
                                if ($test) {
                                    $k--;
                                    break;
                                }
                            }
                            $name = suiji();
                            $post['yqm'] = $code;

                            if (!isset($post['name']) || !$post['name']) {
                                $post['name'] = $name;
                            }
                            if (!isset($post['banned_end_time']) || !$post['banned_end_time']) {
                                $post['banned_end_time'] = null;
                            }

                            if (isset($post['head_portrait'])) {
                                $post['head_100'] = $post['head_300'] = $post['head_portrait'];
                            }

                            $post['role'] = 1;
                            $post['is_online'] = 1;

                            if ($post['sex'] == '男') {
                                $post['attestation'] = 1;
                                $post['is_identity_authentication'] = 2;
                            }

                            $contain[] = $post;
                        }

                        $db = Db::name('user')->insertAll($contain);
                    } else {
                        //生成唯一邀请码
                        for ($i = 2; $i > 1; $i++) {
                            $code = code();

                            $test = Db::table('user')->where('yqm', $code)->select();
                            if (!$test) {
                                $i = 0;
                            }
                        }

                        $post['yqm'] = $code;

                        if (isset($post['name'])) {
                            $nickExist = Db::name('user')->where(['name'=>$post['name'], 'reg'=>1])->count();
                            if ($nickExist) {
                                return ['err' => '昵称已被占用'];
                            }
                        }

                        $db = Db::name('user')->insertGetId($post);

                        ConfigPersonal::createData($db, $post['sex']);
                    }

                    if ($db) {
                        if (isset($good_label) && $good_label) {
                            Labels::edit($good_label, $db);
                        }

                        if (isset($interested_label) && $interested_label) {
                            Labels::edit($interested_label, $db, 2);
                        }

                        (new \app\service\TencentIM)->account_import($db, $post['name'], $post['head_portrait']);


                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {  //修改数据
                    $userInfo = Db::name('user')->find($id);


                    if (isset($post['birthday'])) {
                        $post['age'] = (time() - strtotime($post['birthday'])) / 86400 / 365;
                    } else if (isset($post['age']) && $post['age'] > 0 && $userInfo['age'] != $post['age']) {
                        if ($userInfo['birthday']) {
                            $post['birthday'] = date('Y', strtotime('- '. ($post['age']) . 'year')) . '-' . date('m-d', strtotime($userInfo['birthday']));
                        } else {
                            $post['birthday'] = date('Y-m-d', strtotime('- '. ($post['age']) . 'year') + 86400 * (rand(1, 30)));
                        }
                    }

                    if ($userInfo['yqr'] && (!isset($post['yqr']) || !$post['yqr'] || $post['yqr'] == '')) {
                        $parentInfo = Db::name('user')->where(['yqm' => $userInfo['yqr']])->find();
                        if ($parentInfo && $parentInfo['proxy'] < 1) {
                            unset($post['yqr']);
                        }
                    }

                    if ($post['is_banned']) {
                        if (!$post['banned_end_time']) return ['err' => '先选择冻结时间'];
                        if ($userInfo['banned_end_time'] != $post['banned_end_time']) {
                            Db::name('config_personal')->where(['user_id'=>$id])->update(['unsmstip_switch'=>1, 'is_read_rule'=>0]);
                            $adminLog = [
                                'channel' => 3,
                                'toward' => 0,
                                'money' => 0,
                                'admin' => $admin['name'],
                                'user_id' => $id,
                                'content' => '封禁账号至' . $post['banned_end_time'] . ($post['banned_desc'] ? ' 原因：' . $post['banned_desc'] : '')
                            ];
                            Db::name('privatechat')->where(['type'=>['<>', -1], 'userid'=>$id])->update(['single'=>2]);
                            Db::name('admin_logs')->insert($adminLog);
                            UserPunish::inc($id, 'banned');
                            // Privatechat::notice($userInfo['id'], $adminLog['content'], json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE), 1, -3);
                        }
                    } else {
                        $post['banned_end_time'] = null;
                        if ($userInfo['is_banned']) {
                            Db::name('admin_logs')->insert([
                                'channel' => 3,
                                'toward' => 0,
                                'money' => 0,
                                'admin' => $admin['name'],
                                'user_id' => $id,
                                'content' => '解除账号封禁'
                            ]);
                        }
                    }

                    if (!$post['head_portrait']) {
                        //return ['err' => '请先上传头像'];
                    } else {
                        $post['head_300'] = $post['head_portrait'];
                        $post['head_100'] = $post['head_portrait'];
                    }

                    if (isset($post['password'])) {
                        if (!$post['password']) {
                            unset($post['password']);
                        } else {
                            $post['password'] = User::encryptPassword($post['password']);
                        }
                    }


                    if (isset($post['paypwd']) && $post['paypwd'] === "") {
                        unset($post['paypwd']);
                    } else {
                        $post['paypwd'] = password_hash($post['paypwd'], PASSWORD_DEFAULT);
                    }

                    if (isset($post['phone'])) {
                        
                    if ($post['phone']) {
                        $record = Db::name('user')->where(['phone' => $post['phone']])->find();
                        if ($record) {
                            if ($record['id'] != $id) return ['err' => '手机号已存在'];
                        }
                    }
                    $post['phone'] = $post['phone'] ?: null;
                    }


                    $db = Db::name('user')->where('id', $id)->update($post);

                    if ($db !== false) {
                        // if ($post['age'] != $userInfo['age']) {
                        //     Db::name('config_personal')->where(['user_id'=>$userInfo['id']])->update(['chat_price'=>0,'voice_price'=>0,'video_price'=>0]);
                        // }
                        if (isset($good_label) && $good_label) {
                            Labels::edit($good_label, $id);
                        }

                        if (isset($interested_label) && $interested_label) {
                            Labels::edit($interested_label, $id, 2);
                        }

                        $privacy_update['entertainment'] = $post['entertainment'];
                        if (isset($post['sex']) && $post['sex'] != $userInfo['sex']) {
                            $privacy_update['sex'] = $post['sex'];
                        }
                        Db::name('user')->where(['reg'=>2,'authcode'=>$userInfo['id']])->update($privacy_update);

                        (new \app\service\TencentIM)->account_import($id, $post['name'], $post['head_portrait']);
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    if ($name['dy_program']) {
                        $name['dy_program'] = explode(',',$name['dy_program']);
                    } else {
                        $name['dy_program'] = [];
                    }

                    if ($name['dy_conditions']) {
                        $name['dy_conditions'] = explode(',',$name['dy_conditions']);
                    } else {
                        $name['dy_conditions'] = [];
                    }

                    $good_label = $interested_label = [];

                    $label = LabelsUser::where(['user_id' => $id])->column('id, types, label_id');

                    foreach ($label as $item) {
                        if ($item['types'] == 1) {
                            $good_label[] = $item['label_id'];
                        } else if ($item['types'] == 2) {
                            $interested_label[] = $item['label_id'];
                        }
                    }
                    $name['good_label'] = $good_label;
                    $name['interested_label'] = $interested_label;

                    $otherdata = Db::name('user_repeat_check')->where(['user_id'=>$name['id']])->find();

                    if($otherdata){
                        $otherdata['ips'] = $otherdata['ips'] ? explode(',', $otherdata['ips']) : [];
                        $otherdata['device_ids'] = $otherdata['device_ids'] ? explode(',', $otherdata['device_ids']) : [];
                        $otherdata['zhifucounts'] = $otherdata['zhifucounts'] ? explode(',', $otherdata['zhifucounts']) : [];
                        $otherdata['idcards'] = $otherdata['idcards'] ? explode(',', $otherdata['idcards']) : [];
                        $name['otherdata'] = $otherdata;
                    }
                    $recycleData = Db::name('recycle_user')->where(['user_id'=>$name['id']])->find();
                    if($recycleData){
                        $name['recycleData'] = json_decode($recycleData['data'], true);
                    }

                    $wechat = Db::name('wechat_union')->where(['user_id'=>$id])->find();
                    if (!$wechat) {
                        $wechat = [
                            'unionid'   =>  '',
                            'wxapp_openid'   =>  $name['wechat'],
                            'wxgzh_openid'   =>  '',
                        ];
                    }
                    $name['admin_type'] = $this->adminInfo['type'];
                    $name['wechatInfo'] = $wechat;

                    $name['accessibility'] = Db::name('user_device_accessibility')->where(['user_id'=>$id])->select();

                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }

                $this->assign('id', $id);
            }
            $this->assign('admin', $admin);

            $proxys = Db::name('user')->where(['proxy' => 1])->column('yqm, id, name');
            $this->assign('proxys', $proxys);

            $category = Db::name('dymanic_category')->where(['is_hide' => 0])->order('des asc, id asc')->select();
            $this->assign('category', $category);
            $user_entertainment = Db::name('user_entertainment')->order('sort desc, id asc')->select();
            $this->assign('user_entertainment', $user_entertainment);

            $conditions = Db::name('user_conditions')->where(['hide' => 0])->order('des desc, id asc')->select();
            $conditions_man = [];
            $conditions_woman = [];
            if ($conditions) {
                foreach ($conditions as $k => $v) {
                    if ($v['type'] == 1) {
                        $conditions_man[] = $v;
                    } else {
                        $conditions_woman[] = $v;
                    }
                }
            }
            $this->assign('conditions_man', $conditions_man);
            $this->assign('conditions_woman', $conditions_woman);

            $occupation = Db::name('user_occupation')->where(['hide' => 0])->order('des desc, id asc')->select();
            $this->assign('occupation', $occupation);

            $labels = Db::name('labels')->where(['is_hidden' => 0])->order('sort desc, id asc')->select();
            $this->assign('labels', $labels);

            $this->assign('xuni', $xuni);

            $data = $this->fetch();
        }

        return $data;
    }
    public function ipfenxi(){
        //echo '123';die;
        // 1. 读取所有用户的IP数据
        $users = Db::name('user_repeat_check')->field('user_id, ips')->select();

        // 2. 初始化IP-用户映射数组
        $ipUserMap = [];

        // 3. 拆分IP并构建映射关系
        foreach ($users as $user) {
            $ips = explode(',', $user['ips']);
            foreach ($ips as $ip) {
                $ip = trim($ip);  // 去除可能的空格
                if (!empty($ip)) {
                    $ipUserMap[$ip][] = $user['user_id'];
                }
            }
        }

        // 4. 筛选出被多个用户使用的IP
        $sharedIps = [];
        foreach ($ipUserMap as $ip => $userIds) {
            $uniqueUserIds = array_unique($userIds);
            if (count($uniqueUserIds) > 1) {
                $sharedIps[$ip] = $uniqueUserIds;
            }
        }

        // 5. 输出结果（示例：打印前10个高风险IP）
        arsort($sharedIps);  // 按用户数降序排列
        $sharedIps = array_slice($sharedIps, 0, 10, true);

        foreach ($sharedIps as $ip => $userIds) {
            echo "IP: $ip 被 " . count($userIds) . " 个用户使用: " . implode(',', $userIds) . "<br/><br/>";
        }
    }
    //删除会员
    public function del()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $user = Db::name('user')->where(['id' => $id])->find();
                if (!$user) {
                    return ['err' => '账号不存在'];
                }

                if ($user['delete_time']) {
                    return ['err' => '操作失败'];
                }



                $has = Db::name('recycle_review')->where(['user_id'=>$id, 'state'=>0])->find();
                if(!$has){
                    $contain = [
                        'user_id' => $id,
                        'ip' => (new Whip())->getValidIpAddress(),
                        'os' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                        'create_time' => time(),
                    ];
                    $db = Db::name('recycle_review')->insert($contain);
                }else{
                    $db = true;
                }

                if ($db) {
                    $data = ['ret' => '已提交申请'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function delchats()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $limit = 10000;
                $count = Db::name('privatechat')->where(['userid' => $id])->count();
                $msgs = Db::name('privatechat')->where(['userid' => $id])->order('id','asc')->limit($limit)->select();
                $time = time();
                $delarrs = [];
                $touserids = [];
                $ids = array_column($msgs, 'id');
                foreach ($msgs as $k => $v) {
                    $touserids[] = $v['touserid'];
                    $delarrs[] = ['userid'=>$v['userid'], 'touserid'=>$v['touserid'], 'msg_ids'=>$v['id'], 'create_time'=>$time];
                    $delarrs[] = ['userid'=>$v['touserid'], 'touserid'=>$v['userid'], 'msg_ids'=>$v['id'], 'create_time'=>$time];
                    
                    if(in_array($v['type'], [1,2,3,4])){
                        \app\service\AliOss::delete($v['content']);
                    }
                }
                $touserids = array_unique($touserids);
                Db::name('privatechat_dele_task')->insertAll($delarrs);
                PrivatechatDeleTask::pushtask($id);
                Db::name('chat_lists_records')->where(['user_id' => $id])->delete();
                $delnum = Db::name('privatechat')->where(['id' => ['in', $ids]])->delete();
                $data = ['ret' => '已删除' . $delnum . '条记录,还剩余'. ($count - $delnum) .'条记录'];
                foreach ($touserids as $key => $value) {
                    try {
                        PrivatechatDeleTask::pushtask($value);
                    } catch (Exception $e) {
                        
                    }
                }

            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 批量删除
    public function delAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];

                $db = Db::name('user')->where('id', 'in', $post)->delete();

                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    public function personal()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');
            // if ($post['chat_price'] > 100 || $post['voice_price'] > 100 || $post['video_price'] > 100) {
            //     return ['err' => '输入数额不得超过100'];
            // }

            if ($id) {
                $result = Db::name('config_personal')->where('user_id', $id)->update($post);

                $data = $result ? ['ret' => '修改成功'] : ['err' => '修改失败'];
            }
        } else {
            if ($id) {
                $name = Db::name('config_personal')->where('user_id', $id)->find();

                if (!$name) {
                    $user = Db::name('user')->field('sex')->where(['id' => $id])->find();
                    ConfigPersonal::createData($id, $user['sex']);

                    $name = Db::name('config_personal')->where('user_id', $id)->find();
                }

                $this->assign('name', $name);
            }

            $data = $this->fetch();
        }

        return $data;
    }

    // 快速设置 拒绝 审核 禁止 通过
    public function hide()
    {
        if (request()->isAjax()) {

            $id = input('id') ? input('id') : '0';
            $type = input('type') ? input('type') : '0';
            $text = ['0' => '<font color="#f00">禁止</font>', '1' => '<font color="#1ab394">通过</font>', '2' => '审核', '3' => '<font color="#f00">拒绝</font>'];
            if ($id) {
                $db = Db::name('member')->where('id', $id)->setField('hide', $type);
                if ($db) {
                    $data = [$text[$type]];
                } else {
                    $data = ['删除失败'];
                }
            } else {
                $data = ['GET值错误'];
            }
        } else {
            $data = ['提交错误'];
        }
        return $data;
    }

    // 用户记录
    public function records()
    {
        $money = input('money') ? input('money') : '';
        $type = input('type') ? input('type') : '';
        $data = input('data') ? input('data') : '';
        $where = [];
        if ($type) {
            if ($type == '-1') {
                $where['money'] = 0;
            } else {
                $where['type'] = $type;
            }
        }
        $db = Db::name('member_records')->order('id desc,time desc')->where($where)->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $data = $db->toarray()['data'];
        $type = ['money' => '元', 'score' => '积分', 'jingyan' => '经验值'];
        foreach ($data as $k => $v) {
            if ($v['money']) {
                $data[$k]['text'] = $v['text'] . ' <b id="data1">' . $v['data'] . '</b><b id="data2">' . $v['money'] . '</b> ' . $type[$v['type']];
            }
        }
        $this->assign('data', $data);
        $page = $db->render();
        $this->assign('page', $page);
        $this->assign('type', input('type'));
        return $this->fetch();
    }

    //删除记录  禁用
    public function recordsDel()
    {
        return false;
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('member_records')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //视频认证列表
    public function revideo()
    {
        $map = [];
        $revideo = input('revideo');
        if ($revideo) {
            $map['is_identity_authentication'] = $revideo;
        } else {
            $map['is_identity_authentication'] = ['neq', '0'];
        }
        $this->assign('revideo', $revideo);


        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }


        // $data = Db::table('user')
        //  ->alias('t1')
        //  ->field('t1.*,t2.video as videourl')
        //  ->join('authentication_img t2','t2.user_id = t1.id')
        //  ->where($map)
        //  ->order('t1.revideotime desc,t1.id desc')
        //  ->paginate(_getCachePages(),false,['query'=>request()->param()]);


        $data = Db::name('user')->where($map)->order('revideotime desc,id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //视频认证列表
    public function recar()
    {
        $map = [];
        $recar = input('recar');
        if ($recar) {
            $map['recar'] = $recar;
        } else {
            $map['recar'] = ['neq', '0'];
        }
        $this->assign('recar', $recar);


        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('user')->where($map)->order('recartime desc,id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //视频认证处理
    public function revideoadd()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $validate = validate('Member');

            if ($validate->check($post)) {
                if (!$id) { //添加数据
                    if (!$post['uid']) {
                        return ['err' => '用户ID不能为空'];
                    }
                    $res = Db::name('preach')->where('uid', $post['uid'])->where('state', 'in', '0,1')->select();
                    if ($res) {
                        return ['err' => '用户已申请，待审核或已通过'];
                    }

                    $db = Db::name('preach')->insert($post);
                    if ($db) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {  //修改数据
                    /*$post['revideotime'] = date('Y-m-d H:i:s');*/
                    if (isset($post['is_identity_authentication'])) {
                        if ($post['is_identity_authentication'] == 2) {
                            $post['attestation'] = 1;
                        } else {
                            $post['attestation'] = 0;
                        }
                    }

                    if (isset($post['realname_auth'])) {
                        $postidcard = $post;
                        unset($postidcard['realname_auth']);
                        $post = ['realname_auth'=>$post['realname_auth']];

                        $idcard = Db::name('user_certification')->where(['types'=>1,'user_id'=>$id])->find();
                        $status = ['0'=>0, '3'=>-1, '2'=>1, '1'=>0];
                        if ($idcard) {
                            $postidcard = array_merge($idcard, $postidcard);
                            $postidcard['status'] = $status[$post['realname_auth']]??0;
                            $postidcard['update_time'] = time();
                            Db::name('user_certification')->where(['id'=>$idcard['id']])->update($postidcard);
                        } else {
                            $postidcard['types'] = 1;
                            $postidcard['user_id'] = $id;
                            $postidcard['status'] = $status[$post['realname_auth']]??0;
                            $postidcard['create_time'] = time();
                            Db::name('user_certification')->insert($postidcard);
                        }
                    }


                    Db::name('user')->where('id', $id)->update($post);
                    $data = ['ret' => '修改成功'];
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    $key = input('key', 'is_identity_authentication');
                    // if ($key == 'realname_auth') return '请到【审核中心 - 信息审核】页面修改状态';
                    $this->assign('name', $name);
                    $this->assign('key', $key);

                    if ($key == 'realname_auth') {
                        $idcard = Db::name('user_certification')->where(['types'=>1,'user_id'=>$id])->find();
                        $this->assign('idcard', $idcard);
                    } else if ($key == 'is_identity_authentication') {
                        $auth = Db::name('auth')->where(['user_id'=>$id])->find();
                        $this->assign('auth', $auth);
                    }
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //车辆认证处理
    public function recaradd()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $validate = validate('Member');

            if ($validate->check($post)) {
                if (!$id) { //添加数据
                    if (!$post['uid']) {
                        return ['err' => '用户ID不能为空'];
                    }
                    $res = Db::name('preach')->where('uid', $post['uid'])->where('state', 'in', '0,1')->select();
                    if ($res) {
                        return ['err' => '用户已申请，待审核或已通过'];
                    }

                    $db = Db::name('preach')->insert($post);
                    if ($db) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {  //修改数据
                    $post['recartime'] = date('Y-m-d H:i:s');

                    $db = Db::name('user')->where('id', $id)->update($post);
                    if ($db) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //认证视频预览
    public function watch()
    {
        if (!input('?id')) {
            $this->error("参数错误");
        }
        $id = input('id/d');
        $name = Db::name('authentication_img')->where(['user_id' => $id])->find();
        $this->assign('name', $name);
        return $this->fetch();
    }

    //vip档位
    public function vipstyle()
    {
        $map = [];
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        } else {
            $map = '';
        }

        $data = Db::name('vip_style')->where($map)->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //添加修改vip
    public function vipdwadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (($post['times'] == 'day' && $post['keep'] >= 30) ||
                ($post['times'] == 'month' && $post['keep'] >= 12)) {
                return ['err' => '有效期数值超出范围'];
            }

            if (!$id) {
                $db = Db::name('vip_style')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {//修改数据

                $db = Db::name('vip_style')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('vip_style')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除vip档位
    public function vipdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('vip_style')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //vip购买订单
    public function viporder()
    {
        $map = [];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');

        if ($type == 1) {
            $map['t1.type'] = '0';
        } else if ($type == 2) {
            $map['t1.type'] = '1';
        } else if ($type == 3) {
            $map['t1.pay'] = '1';
        } else if ($type == 4) {
            $map['t1.pay'] = '2';
        } else if ($type == 5) {
            $map['t1.pay'] = '3';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $date = input('date');
        if ($date) {
            $map['t1.time'] = ['like', '%' . $date . '%'];
        }

        $map['t1.desc'] = ['not like', '%后台添加'];

        $data = Db::table('vip_order t1')
            ->field('t1.*,t2.name, t3.name, t3.description')
            ->join('user t2', 't2.id = t1.user_id')
            ->join('vip_style t3', 't1.sid = t3.id')
            ->where($map)
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $map['t1.type'] = 1;

        $sum = Db::table('vip_order t1')->join('user t2', 't2.id = t1.user_id')->where($map)->sum('price');

        $this->assign('sum', $sum);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //删除vip购买订单
    public function orderdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('vip_order')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //提现管理
    public function tixian()
    {
        $map = ['channel'=>1];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';

        $type = input('type');
        if ($type == 1) {
            $map['t1.paymethod'] = '0';
        } else if ($type == 2) {
            $map['t1.paymethod'] = '1';
        } else if ($type == 3) {
            $map['t1.state'] = '0';
        } else if ($type == 4) {
            $map['t1.state'] = '1';
        } else if ($type == 5) {
            $map['t1.state'] = '2';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');

        $this->assign('search_name', $search_name);
        $this->assign('search_type', $search_type);
        $mapStr = '';
        if ($search_name && $search_type) {
            if (in_array($search_type, ['zhifucount', 'zhifuname'])) {
                $mapStr = 't2.' . $search_type . ' like "%' . $search_name . '%" or t1.data like "%' . $search_name . '%"';
            } else {
                if (in_array($search_type, ['userid', 'order_no'])) {
                    $map['t1.' . $search_type] = $search_name;
                } else {
                    $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
                }
            }
        }
        $yesterday = input('yesterday');
        $start = input('start');
        $end = input('end');
        if($yesterday && !$start && !$end){
            $date = date('Y-m-d');
            $yesterday_start = date('Y-m-d', strtotime('-1 day', strtotime($date)));
            $start = $yesterday_start . ' 00:00:00';
            $end = $yesterday_start . ' 23:59:59';
        }
        if ($start && $end) {
            $map['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $map['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['t1.create_time'] = ['elt', strtotime($end)];
        }
        $map['t1.paymethod'] = '2';//此列表改为只展示银行卡提现
        $map['t1.sfmntx'] = '0';//非模拟提现
        $data = Db::name('withdraw t1')
            ->master()
            ->field('t1.*,t2.name,t2.quality,t3.user_id as withdraw_limit')
            ->join('user t2', 't2.id = t1.userid', 'left')
            ->join('withdraw_limit t3', 't3.user_id = t1.userid', 'left')
            ->where($map)
            ->where($mapStr)
            ->order('t1.update_time desc, t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item)
            {
                $fzstatus=$item['status'];
                if ($item['paymethod'] == 2) {
                    $status = ['待分账','部分分账','分账完成'];
                    $btn_style = ['danger','success','primary'];
                    $item['status_text'] = $status[$item['status']]??'';
                    $item['btn_style'] = $btn_style[$item['status']]??'';
                    $item['withdraw_limit'] = $item['withdraw_limit'] > 0 ? true : false;
                }
                   //此处查询汇付分账是否成功
                $item['hf_status']='<span style="">--</span>';
                if($item['status']==2 && $item['txstate']!=1) {//本地分账完成
                    $order_no = $item['order_no'];
                    $res = Db::name('withdraw_recharge_mapping')
                        ->where('withdraw_no', $order_no)     // 等值查询
                        ->whereNull('confirm_order_no')       // NULL值查询
                        ->select();
                    //echo Db::name('withdraw_recharge_mapping')->getlastsql();die;
                    if($res && $item['request_time']){//汇付分账有失败的
                        $errnum=count($res);
                        $item['hf_status'] = '<span style="color:red;">有失败'.$errnum.'</span>';
                    }elseif(!$res && $item['request_time']){
                        $item['hf_status'] = '<span style="color:blue;">全成功</span>';
                    }else{
                        $item['hf_status'] = '<span style="color:green;">分账中</span>';
                    }
                }elseif($fzstatus==1){//本地分账未完成
                    $item['hf_status'] = '<span style="color:green;">分账中</span>';
                }else{
                    $item['hf_status'] = '<span style="">--</span>';
                }
                return $item;
            });
        //print_r($data);
        $sum = Db::table('withdraw t1')->join('user t2', 't2.id = t1.userid','left')->where($map)->where($mapStr)->sum('money');

        $this->assign('sum', round($sum, 2));
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
    
        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('admin', $admin);

        return $this->fetch();
    }
        //汇付模拟提现
    public function mntixian()
    {
        $map = ['channel'=>1];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        if(!in_array($admin['id'],[1,2])){//非超管、非kefu01显示无权限
            echo '无权使用此功能！';die;
        }
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';

        $type =4;//默认审核通过的
        if ($type == 1) {
            $map['t1.paymethod'] = '0';
        } else if ($type == 2) {
            $map['t1.paymethod'] = '1';
        } else if ($type == 3) {
            $map['t1.state'] = '0';
        } else if ($type == 4) {
            $map['t1.state'] = '1';
        } else if ($type == 5) {
            $map['t1.state'] = '2';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');

        $this->assign('search_name', $search_name);
        $this->assign('search_type', $search_type);
        $mapStr = '';
        if ($search_name && $search_type) {
            if (in_array($search_type, ['zhifucount', 'zhifuname'])) {
                $mapStr = 't2.' . $search_type . ' like "%' . $search_name . '%" or t1.data like "%' . $search_name . '%"';
            } else {
                if (in_array($search_type, ['userid', 'order_no'])) {
                    $map['t1.' . $search_type] = $search_name;
                } else {
                    $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
                }
            }
        }
        $yesterday = input('yesterday');
        $start = input('start');
        $end = input('end');
        if($yesterday && !$start && !$end){
            $date = date('Y-m-d');
            $yesterday_start = date('Y-m-d', strtotime('-1 day', strtotime($date)));
            $start = $yesterday_start . ' 00:00:00';
            $end = $yesterday_start . ' 23:59:59';
        }
        if ($start && $end) {
            $map['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $map['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['t1.create_time'] = ['elt', strtotime($end)];
        }
        $map['t1.paymethod'] = '2';//此列表改为只展示银行卡提现
        $map['t1.sfmntx'] = 1;//模拟提现
        $data = Db::name('withdraw t1')
            ->master()
            ->field('t1.*,t2.name,t2.quality,t3.user_id as withdraw_limit')
            ->join('user t2', 't2.id = t1.userid', 'left')
            ->join('withdraw_limit t3', 't3.user_id = t1.userid', 'left')
            ->where($map)
            ->where($mapStr)
            ->order('t1.update_time desc, t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item)
            {
                if ($item['paymethod'] == 2) {
                    $status = ['待分账','部分分账','分账完成'];
                    $btn_style = ['danger','success','primary'];
                    $item['status_text'] = $status[$item['status']]??'';
                    $item['btn_style'] = $btn_style[$item['status']]??'';
                    $item['withdraw_limit'] = $item['withdraw_limit'] > 0 ? true : false;
                }
                return $item;
            });


        $sum = Db::table('withdraw t1')->join('user t2', 't2.id = t1.userid','left')->where($map)->where($mapStr)->sum('money');

        $this->assign('sum', round($sum, 2));
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('admin', $admin);

        return $this->fetch();
    }
    //模拟提现添加
    public function mntixianadd()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            //print_r($post);die;
            $userid=$post['userid'];
            $hfdh=$post['hfdh'];
            $money=$post['money'];
            $mnreson=$post['mnreson'];
            if(!$userid || !is_numeric($userid)){
                return ['err' => '提现用户id必填且只能是正常数字'];
            }
            if(!$hfdh){
                return ['err' => '汇付单号必填'];
            }
            if(!$money || !is_numeric($money)){
                return ['err' => '提现金额必填且只能是大于0的数字'];
            }
            if(!$mnreson){
                return ['err' => '说明必填，尽量要做到规范统一，方便追查'];
            }
            $user=Db::name('user')->where('id',$userid)->find();
            if(!$user){
                return ['err' => '用户不存在，请检查'];
            }
            $order = Db::name('order_info')->where('data', 'like', '%' . $hfdh . '%')->find();
            //echo Db::name('order_info')->getLastSql();die;
            if(!$order){
                return ['err' => '订单不存在，请检查'];
            }
            $data = ['name' => $user['bank'], 'bank_user_name' => $user['bank_user_name'], 'account' => $user['bank_number']];
            $data=json_encode($data, JSON_UNESCAPED_UNICODE);
            $order_no = uniqid('w'.$userid.'n');
            //echo $order_no;die;
            try{
                //开启事务
                Db::startTrans();
            $dataall=[
                "userid" => $userid,
                "paymethod" => 2,
                "money" => $money,
                'price' => $money*10,
                'shouxu' => $money*10*0.08,
                'data' => $data,
                'state'=>1,
                'create_time'=> time(),
                'update_time' => time(),
                'expire_time' => time() + 60 * 60 * 24,
                'order_no'=>$order_no,
                'sfmntx' => '1',
                'mnreson' => $mnreson
            ];
                //$insert = Db::name('withdraw')->fetchSql(true)->insert($dataall);
                //echo $insert;die;
                $insert = Db::name('withdraw')->insert($dataall);

                $insertId = $insert ? Db::getLastInsID() : 0;
                //此处立马将分账的订单余额清0
                $orderid=$order['id'];
                $updan=Db::name('order_info')->where('id',$orderid)->update(['remain_mntx'=>$order['remain_amount'],'remain_amount'=>0]);
                if($insert && ($updan!==false)) {
                    $withdraw = Db::name('withdraw')->where('id', $insertId)->find();
                    if ($withdraw && $withdraw['paymethod'] == 2 && $withdraw['state'] == 1) {
                        // 推入Redis队列
                        $jobData = [
                            "userid" => $withdraw['userid'],
                            'withdraw_no' => $withdraw['order_no'],
                            'create_time' => time()
                        ];

                        $redisQueue = new RedisQueue();
                        $isPushed = $redisQueue->push('withdraw', $jobData);
                    }
                    if($isPushed){
                        Db::commit();
                        return ['ret' => '添加成功'];
                    }else {
                        Db::rollback();
                        return ['err' => '添加失败1'];
                    }
                }else{
                    Db::rollback();
                    return ['err' => '添加失败2'];
                }
            }catch (\Exception $e){
                echo $e->getMessage();
                Db::rollback();
                return ['err' => '添加失败3'];
            }
        }
        return $this->fetch();
    }
       //提现管理 支付宝
    public function tixian_zfb()
    {
        $map = ['channel'=>1];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';

        $type = input('type');
        if ($type == 1) {
            $map['t1.paymethod'] = '0';
        } else if ($type == 2) {
            $map['t1.paymethod'] = '1';
        } else if ($type == 3) {
            $map['t1.state'] = '0';
        } else if ($type == 4) {
            $map['t1.state'] = '1';
        } else if ($type == 5) {
            $map['t1.state'] = '2';
        }
        $daochu = input('daochu');
        if($daochu==2){//未导出
            $map['t1.zhifubao_export_no'] = ['null', ''];
        }elseif($daochu==1){//已导出
            $map['t1.zhifubao_export_no'] = ['not null', ''];
        }
        $this->assign('daochu',$daochu);
        
        $search_name = input('param.name');
        $search_type = input('param.search');

        $this->assign('search_name', $search_name);
        $this->assign('search_type', $search_type);
        $mapStr = '';
        if ($search_name && $search_type) {
            if (in_array($search_type, ['zhifucount', 'zhifuname'])) {
                $mapStr = 't2.' . $search_type . ' like "%' . $search_name . '%" or t1.data like "%' . $search_name . '%"';
            } else {
                if (in_array($search_type, ['userid', 'order_no'])) {
                    $map['t1.' . $search_type] = $search_name;
                } else {
                    $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
                }
            }
        }
        $yesterday = input('yesterday');
        $start = input('start');
        $end = input('end');
        if($yesterday && !$start && !$end){
            $date = date('Y-m-d');
            $yesterday_start = date('Y-m-d', strtotime('-1 day', strtotime($date)));
            $start = $yesterday_start . ' 00:00:00';
            $end = $yesterday_start . ' 23:59:59';
        }
        if ($start && $end) {
            $map['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $map['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['t1.create_time'] = ['elt', strtotime($end)];
        }
        $map['t1.paymethod'] = '1';//此列表改为只展示支付宝提现
        $data = Db::name('withdraw t1')
            ->master()
            ->field('t1.*,t2.name,t2.quality')
            ->join('user t2', 't2.id = t1.userid', 'left')
            ->where($map)
            ->where($mapStr)
            ->order('t1.update_time desc, t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item)
            {
                if ($item['paymethod'] == 2) {
                    $status = ['待分账','部分分账','分账完成'];
                    $btn_style = ['danger','success','primary'];
                    $item['status_text'] = $status[$item['status']]??'';
                    $item['btn_style'] = $btn_style[$item['status']]??'';
                }
                return $item;
            });


        $sum = Db::table('withdraw t1')->join('user t2', 't2.id = t1.userid','left')->where($map)->where($mapStr)->sum('money');

        $this->assign('sum', round($sum, 2));
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('admin', $admin);

        return $this->fetch();
    }
    //支付宝提现 打款状态设置
    public function tixian_zfbdk()
    {
        $id = input("id/d");
        $txstate = input("txstate");
        if (request()->isAjax()) {
            if (!$id) {
                $data = ['err' => '数据id必传！'];
            } else {
                //$updates = ['txstate' => $txstate, 'update_time' => time()];
                $updates = ['txstate' => $txstate];
                $withdraw = Db::name('withdraw')->find($id);
                if($withdraw){
                    $txstateup=Db::name('withdraw')->where('id', $id)->update($updates);
                    if($txstateup){
                        $data = ['ret' => '修改成功'];
                    }else{
                        $data = ['ret' => '修改失败'];
                    }
                }else{
                    $data = ['ret' => '未找到数据'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('withdraw')->find($id);
                if($name){
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }
    
    //支付宝提现 批量打款状态设置
    public function pldkok_zfb(){
        $ids = input('ids');
        $ok = Db::name('withdraw')->where(['id' => ['in', $ids], 'state'=>1,'paymethod'=>1])->update(['txstate'=>1]);
        if($ok!==false){
            return ['ret' => '操作成功'];
        }else{
            return ['err' => '操作失败'];
        }
    }
    
    public function tixianadd()
    {
        $id = input("id/d");

        $state = input("state");
        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {

                $db = Db::name('withdraw')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $updates = ['state' => $state, 'update_time' => time()];

                $withdraw = Db::name('withdraw')->find($id);

                // 启动事务
                Db::startTrans();
                try {
                    if ($state == 2) {
                        $content = '提现申请驳回';

                        $reason = input('reason');
                        if ($reason) {
                            $updates['reason'] = input('reason');

                            $content .= '。理由：' .$reason;
                        }
                        //返还
                        Income::index($withdraw['userid'], 0, $withdraw['price'] + $withdraw['shouxu'], $content, 1);
                    } else {
                        // if ($withdraw['paymethod'] == 2) {
                        //     if ($withdraw['status'] != 2) {
                        //         return ['err'=>'分账未完成，请稍后处理'];
                        //     }
                        // }
                        $datas = json_decode($withdraw['data'], true);

                        if (!isset($datas['name']) || !$datas['name']) {
                            return ['err' => '未填写提现到款账户姓名'];
                        }

                        if (!isset($datas['account']) || !$datas['account']) {
                            return ['err' => '未填写提现到款账户'];
                        }

                        $datas['order_id'] = input('order_id/s', '');
                        $updates['data'] = json_encode($datas, JSON_UNESCAPED_UNICODE);

                        Db::name('platform_balance')->insert(['types' => 1, 'money' => $withdraw['money'], 'content' => '用户(ID:' . $withdraw['userid'] . ')提现', 'create_time' => time()]);
                    }

                    $res= Db::name('withdraw')->where('id', $id)->update($updates);

                    if ($res) {
                        if ($withdraw['paymethod'] == 2 && $state == 1) {
                            // 推入Redis队列
                            $jobData = [
                                "userid" => $withdraw['userid'],
                                'withdraw_no' => $withdraw['order_no'],
                                'create_time' => time()
                            ];
                            
                            $redisQueue = new RedisQueue();
                            $isPushed = $redisQueue->push('withdraw', $jobData);

                            // $result = action('api/adapay/drawcash', [
                            //     'member_id'=>$withdraw['userid'],
                            //     'cash_amt'=>$withdraw['money'],
                            //     'order_no'=>$withdraw['order_no']
                            // ]);
                            // $result = $result->getData();
                            // if ($result['code']!=200) {
                            //     Db::rollback();
                            //     return ['err'=>$result['msg']];
                            // }
                        }
                    }

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ['err' => $e->getMessage()];
                }
                $data = ['ret' => '修改成功'];
            }
        } else {
            if ($id) {
                $name = Db::name('withdraw')->find($id);
                if ($name) {
                    //此处在进行当前提现用户 一天内提现的总金额查询
                    // 获取当前订单的创建日期
                    $orderDate = date('Y-m-d', $name['create_time']);
                    $startTime = strtotime($orderDate);
                    $endTime = $startTime + 86400; // 一天后
                    
                    // 查询该用户在订单创建日当天审核通过(state=2)的提现总金额
                    $totalAmount = Db::name('withdraw')
                        ->where('userid', $name['userid'])  // 同一用户
                        ->where('create_time', '>=', $startTime)  // 当天开始
                        ->where('create_time', '<', $endTime)     // 当天结束
                        ->where('state', 1)  // 状态为审核通过
                        ->sum('money');
                    
                    // 根据金额设置不同颜色的提示
                    if ($totalAmount > 5000) {
                        $this->assign('withdraw_tip', [
                            'type' => 'danger',  // 红色提示
                            'message' => "该用户今日已申请审核通过的提现 {$totalAmount} 元，已超过5000元上限"
                        ]);
                    } else {
                        $this->assign('withdraw_tip', [
                            'type' => 'success',  // 绿色提示
                            'message' => "该用户今日已申请审核通过的提现 {$totalAmount} 元，未超过5000元上限"
                        ]);
                    }
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除提现记录
    public function tixiandel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('withdraw')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //充值管理
    public function topup()
    {
        $state = input('state');


        $order = input('order/d', 1);
        $this->assign('order', $order);
        $ordersort = ['t1.addtime desc', 't1.addtime asc'];

        $map = ['t1.type' => ['neq', 3], 'state' => ['neq', 2], 'sys_channel'=>1];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';
        //$sum = db('topup')->alias('t1')->join('user t2', 't2.id = t1.fk_userid')->where($daili)->sum('t1.price');
        //$month = db('topup')->alias('t1')->join('user t2', 't2.id = t1.fk_userid')->where($daili)->where('addtime', 'like', date('Y-m') . '%')->sum('t1.price');

        if ($state !== null) {
            $map['t1.state'] = $state;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if ($search_type=='id'){
                $map['t1.fk_userid'] = $search_name;
            }else if ($search_type=='numbers'){
                $map['t1.numbers'] = $search_name;
            }else if ($search_type == 'payer') {
                $map['t1.data'] = ['exp', Db::raw("like '%openid\":\"$search_name\"%' or t1.data like '%buyer_id\":\"$search_name\"%'")];
            }else{
                $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $start = input('start');
        $end = input('end');
        if (input('last_month', 0)) {
            $start = (date('m') == 1 ? date('Y') - 1 : date('Y')) . '-' . (date('m') == 1 ? 12 : date('m') - 1) . '-01 00:00:00';
            $end = date('Y-m') . '-01 00:00:00';
        }
        if ($start && $end) {
            $map['t1.addtime'] = ['between', [date('Y-m-d H:i:s', strtotime($start)), date('Y-m-d H:i:s', strtotime($end))]];
        } else if ($start && !$end) {
            $map['t1.addtime'] = ['egt', date('Y-m-d H:i:s', strtotime($start))];
        } else if (!$start && $end) {
            $map['t1.addtime'] = ['elt', date('Y-m-d H:i:s', strtotime($end))];
        }

        $data = Db::table('topup')
            ->alias('t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.fk_userid', 'inner')
            ->where($map)
            ->order($ordersort[$order - 1])
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function($item)
            {
                $item['platform_user_id'] = '';
                if ($item['data']) {
                    $notifyData = json_decode($item['data'], true);
                    $item['platform_user_id'] = isset($notifyData['openid']) ? $notifyData['openid'] : (isset($notifyData['buyer_id'])?$notifyData['buyer_id']:($notifyData['buyer_user_id']??''));
                }
                return $item;
            });

        $sum = Db::table('topup t1')->join('user t2', 't2.id = t1.fk_userid', 'inner')->where($map)->sum('t1.price');
        
        $atypeid=$admin['type'];
        //echo $atypeid;
        if($atypeid==7 && !$search_name){//法律顾问 不检索不显示变动金额
            $sum=0;
            $data=array();
            $this->assign('sum', round($sum, 2));
            $this->assign('data', $data);
            $page='';
            $this->assign('page', $page);
        }else{
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
        }
        
        $this->assign('sum', round($sum, 2));
        $this->assign('state', $state);

        $this->assign('start', $start);
        $this->assign('end', $end);

        return $this->fetch();
    }

    //删除充值记录
    public function topupdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('topup')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //特权分组
    public function tequan()
    {
        $data = Db::name('tequan_type')->where(['id' => 1])->order('des desc,id asc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    // 添加分组
    public function typeadd()
    {
        $id = input("id");
        if (request()->isAjax()) {

            $post = input('post.');
            $time = time();
            $post['update_time'] = $time; //更新时间
            if (!$id) {   // 添加数据
                $titledb = Db::name('tequan_type')->where('title', $post['title'])->find();
                if ($titledb) {
                    return ['err' => '分组标题已存在'];
                }
                $post['create_time'] = $time; // 添加时间
                $db = Db::name('tequan_type')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                $db = Db::name('tequan_type')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('tequan_type')->where('id', $id)->find();
                //var_dump($name);die();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 特权次数列表
    public function lists()
    {
        $tid = input('tid');

        if ($tid == 1) {
            $data = Db::name('vip_config')->where('id', 1)->select();
        } else if ($tid == 2) {
            $data = Db::name('num_config')->order('id desc')->select();
        } else if ($tid == 3) {
            $data = Db::name('vip_config')->where('id', 2)->select();
        }

        $this->assign('tid', $tid);
        $this->assign('data', $data);

        return $this->fetch('list');
    }

    // 特权添加、修改
    public function tequanadd()
    {
        $id = input("id");
        $tid = input("tid");

        $this->assign('tid', input("tid"));
        $slide_type = Db::name('tequan_type')->select();
        $this->assign('tequan_type', $slide_type);

        if (request()->isAjax()) {
            $post = input('post.');
            if ($id) {
                if (in_array($tid, [1,3])) {
                    $arr = [
                        'count' => $post['count'],
                        'time' => date('Y-m-d H:i:s')
                    ];
                    $db = Db::name('vip_config')->where('id', $id)->update($arr);
                } else if ($tid == 2) {
                    $arr = [
                        'name' => $post['name'],
                        'money' => $post['money'],
                        'time' => date('Y-m-d H:i:s')
                    ];
                    $db = Db::name('num_config')->where('id', $id)->update($arr);
                }

                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                if (in_array($tid, [1,3])) {
                    $name = Db::name('vip_config')->find($id);
                } else if ($tid == 2) {
                    $name = Db::name('num_config')->where('id', $id)->find();
                }

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //会员照片管理
    public function image()
    {
        $id = input('id');

        $data = Db::name('user_img')->where('user_id', $id)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //删除照片
    public function imgdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            $userimg = Db::table('user_img')->where('id', $id)->find();

            if ($userimg) {
                $db = Db::name('user_img')->delete($id);
                if ($db) {
                    if ($userimg['is_auth'] == 0) {
                        $imagea = json_decode($userimg['pic']);
                        $imageb = json_decode($userimg['picthumb']);
                        $images = array_merge($imagea,$imageb);
                        foreach ($images as $key => $value) {
                            \app\service\AliOss::delete($value);
                        }
                    }
                    
                    /*$context = ['desc' => "图片不合法,已被系统屏蔽"];
                    $arr = [
                        'to_user' => $uid,
                        'context' => json_encode($context, JSON_UNESCAPED_UNICODE),
                        'type' => 2
                    ];
                    Db::table('sys_message')->insert($arr);*/
    
                    Cache::rm('photos' . $userimg['user_id']);
                    Cache::rm('photosCount' . $userimg['user_id']);

                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //照片付费管理
    public function zpfufei()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.time'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            if ($search_type == 'id') {
                $where['t1.' . $search_type] = $search_name;
            } else if ($search_type == 'uid') {
                $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
                $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = Db::table('packet_img')
            ->alias('t1')
            ->field('t1.*,t2.name,t3.pic')
            ->join('user t2', 't2.id = t1.to_user')
            ->join('user_img t3', 't3.id = t1.img_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.time desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //相册付费管理
    public function xcfufei()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.time'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
            $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::table('auth_img')
            ->alias('t1')
            ->field('t1.*,t2.name,t2.head_portrait')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.time desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //关注管理
    public function attention()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.addtime'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
            $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::table('attention')
            ->alias('t1')
            ->field('t1.*,t2.name,t2.head_portrait')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.addtime desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //关注管理
    public function blacklist()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.addtime'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
            $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::table('blacklist')
            ->alias('t1')
            ->field('t1.*,t2.name,t2.head_portrait')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.addtime desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //取消关注
    public function gzdel()
    {
        if (request()->isAjax()) {

            $id = input('id');

            if ($id) {
                $db = Db::name('attention')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //取消拉黑
    public function lhdel()
    {
        if (request()->isAjax()) {

            $id = input('id');

            if ($id) {
                $db = Db::name('blacklist')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function location()
    {
        $action = input('action');
        $id = input('id/d');

        $this->assign('action', $action);
        $this->assign('id', $id);
        return $this->fetch();
    }

    //照片管理
    public function imglist()
    {
        $where = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.time'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }

        $is_face = input('is_face/d', 0);
        if($is_face){
            $where['t1.is_face'] = $is_face;
        }
        $this->assign('is_face', $is_face);

        $status = input('status/d');

        if ($status === null) {
            $status = 0;
        }
        if ($status == 999) {
            
        } else if ($status == 998) {
            $where['t1.delete_time'] = ['>', 0];
        } else {
            $where['t1.status'] = $status;
        }
        $this->assign('status', $status);

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t1.'.$search_type] = ['like', '%' . $search_name . '%'];
        }

        // $data = Db::name('user_img')->where($where)->order('time desc')->paginate(_getCachePages(),false,['query'=>request()->param()]);


        $data = Db::table('user_img')
            ->alias('t1')
            ->field('t1.*,t2.name, t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->order('time desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function($item)
            {
                if ($item['is_face']) {
                    $item['authpic'] = Db::name('auth')->where(['user_id'=>$item['user_id']])->value('image1');
                }
                return $item;
            });

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //标签列表
    public function tags()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $order = input('order') ? input('order') : 'asc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        $data = db('tags')->where($where)->order('des ' . $order . ',id ' . $order)->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    //添加标签
    public function tagsadd()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input();

            if (!$id) { //添加数据
                unset($post['url']);
                $res = db('tags')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                unset($post['url']);
                $res = db('tags')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('tags')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除标签
    public function tagsDel()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('tags')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 充值选项
    public function topupcate()
    {
        $channel_sex = input('channel_sex', 2);

        $data = Db::name('topup_select')->where(['channel_sex'=>$channel_sex])->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $nobles = Db::name('grade_noble')->column('id, name');
        $cars = Db::name('car')->where(['is_hidden' => 0])->column('id, name');

        $this->assign('nobles', $nobles);
        $this->assign('cars', $cars);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        $this->assign('channel_sex', $channel_sex);

        return $this->fetch();
    }

    // 添加/编辑充值选项
    public function topupcateadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            // $config = Config::index('', 'rate');
            // if($post['price'] * $config['rate'] < $post['money']){
            //     return ['err' => '金币比例过高'];
            // }

            if (!$id) {//添加数据
                $db = Db::name('topup_select')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {//修改数据
                $db = Db::name('topup_select')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('topup_select')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $nobles = Db::name('grade_noble')->select();
            $cars = Db::name('car')->where(['is_hidden' => 0])->select();

            $this->assign('nobles', $nobles);
            $this->assign('cars', $cars);

            $data = $this->fetch();
        }
        return $data;
    }

    // 删除充值选项
    public function topupcatedel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('topup_select')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 敏感词列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function mingan()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = db('filter_word')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    //添加标签
    public function minganadd()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('');

            unset($post['url']);

            if (!$id) { //添加数据
                $record_id = Db::name('filter_word')->where(['name' => $post['name']])->value('id');
                if ($record_id) return ['err' => '敏感词已存在'];

                $res = db('filter_word')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $record_id = Db::name('filter_word')->where(['name' => $post['name']])->value('id');
                if ($record_id != $id) return ['err' => '敏感词已存在'];

                $res = db('filter_word')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('filter_word')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除标签
    public function minganDel()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('filter_word')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 记录用户查看阅读即焚的照片时手机操作截屏照片
     */
    public function screenshotRecord()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            if ($search_type == 'id') {
                $where[$search_type] = $search_name;
            } else {
                $where['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $where['t1.num'] = ['gt', 1];
        $data = Db::name('screenshot_records t1')->field('t1.*, t2.name, t2.phone')->join('user t2', 't2.id = t1.user_id')->where($where)->order('t1.update_time desc, t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function editrecords()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if ($id) {  //修改数据
                if (!$post['banned_end_time']) return ['err' => '先选择冻结时间'];

                $data = Db::name('screenshot_records')->where('id', $id)->find();

                Db::name('screenshot_records')->where('id', $id)->setField('status', 1);
                $db = Db::name('user')->where('id', $data['user_id'])->update(['banned_end_time' => $post['banned_end_time'], 'is_banned' => 1]);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delrecords()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('screenshot_records')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function addimage()
    {
        if (request()->isAjax()) {

            $post = input('');

            if (!isset($post['masterimg']) || !$post['masterimg']) {
                return ['err' => '至少需上传一张图片'];
            }

            if ($post['burn'] == 2) {
                if (!isset($post['packet']) || !$post['packet']) {
                    return ['err' => '输入红包金额'];
                }
                $post['burn'] = 0;
            }

            $post['masterimg'] = explode(',', $post['masterimg']);
            //$post['masterimg'][0] = substr($post['masterimg'][0], 6);

            $con = [];
            foreach ($post['masterimg'] as $k => $v) {
                $con[] = [
                    'user_id' => $post['id'],
                    'pic' => json_encode([$v]),
                    'picthumb' => json_encode([$v]),
                    //'picthumb' => json_encode([substr($v, 0, 15) . 'thumb' . substr($v, 15)]),
                    'burn' => $post['burn'] ?? 0,
                    'packet' => $post['packet'] ?? 0,
                ];
            }

            $result = Db::name('user_img')->insertAll($con);
    
            Cache::rm('photos' . $post['id']);
            Cache::rm('photosCount' . $post['id']);

            if ($result) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function addvideo()
    {
        if (request()->isAjax()) {

            $post = input('');

            if (!isset($post['cover']) || !$post['cover']) {
                return ['err' => '请先上传封面图'];
            }

            if (!isset($post['pic']) || !$post['pic']) {
                return ['err' => '请先上传视频'];
            }

            if ($post['burn'] == 2) {
                if (!isset($post['packet']) || !$post['packet']) {
                    return ['err' => '输入红包金额'];
                }
                $post['burn'] = 0;
            }

            $con = [
                'user_id' => $post['id'],
                'cover' => $post['cover'],
                'pic' => json_encode([$post['pic']]),
                'picthumb' => '',
                'burn' => $post['burn'] ?? 0,
                'packet' => $post['packet'] ?? 0,
                'types' => 2
            ];

            $result = Db::name('user_img')->insert($con);
    
            Cache::rm('photos' . $post['id']);
            Cache::rm('photosCount' . $post['id']);

            if ($result) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function all()
    {
        //if (request()->isAjax()) {
        $post = input('')["delAll"];
        //$type = input('type');

        if ($post) {
            //$post = $post['delAll'];

            $result = Db::table('vip_order')
                ->alias('t1')
                ->field('t1.*,t2.name, t3.name, t3.description')
                ->join('user t2', 't2.id = t1.user_id')
                ->join('vip_style t3', 't1.sid = t3.id')
                ->where(['t1.id' => ['in', $post]])
                ->select();

            foreach ($result as $k => $v) {
                if ($v['pay'] == 1) {
                    $result[$k]['pay'] = '微信';
                } else if ($v['pay'] == 2) {
                    $result[$k]['pay'] = '支付宝';
                } else if ($v['pay'] == 3) {
                    $result[$k]['pay'] = '余额';
                }

                if ($v['type'] == 1) {
                    $result[$k]['type'] = '已支付';
                } else {
                    $result[$k]['type'] = '未支付';
                }
            }

            $this->installExcel($result);

            if (1) {
                $data = ['ret' => '成功'];
            } else {
                $data = ['err' => '失败'];
            }
        } else {
            $data = ['err' => '失败，未选中数据'];
        }
        /*} else {
            $data = ['err' => '提交类型错误'];
        }*/
        return $data;
    }

    public function installExcel($data)
    {
        // 从数据库查询需要的数据
        // $data = model('admin/Loginlog')->where($where)->order('id','desc')->select();
        // Create new Spreadsheet object
        $spreadsheet = new Spreadsheet();

        // Add title
        $spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', '订单号')
            ->setCellValue('B1', '用户id')
            ->setCellValue('C1', '用户昵称')
            ->setCellValue('D1', '支付方式')
            ->setCellValue('E1', '支付状态')
            ->setCellValue('F1', '支付详情')
            ->setCellValue('G1', '支付时间')
            ->setCellValue('H1', '备注');
        // Rename worksheet
        $spreadsheet->getActiveSheet()->setTitle('订单情况');
        $i = 2;
        foreach ($data as $v) {
            //$name = isset($rs['name'][$k]) ? $rs['name'][$k] : 'undefined';
            // Add data
            $spreadsheet->getActiveSheet()
                ->setCellValue('A' . $i, $v['vip_order'])
                ->setCellValue('B' . $i, $v['user_id'])
                ->setCellValue('C' . $i, $v['name'])
                ->setCellValue('D' . $i, $v['pay'])
                ->setCellValue('E' . $i, $v['type'])
                ->setCellValue('F' . $i, $v['name'] . ' / ' . $v['price'])
                ->setCellValue('G' . $i, date('Y-m-d H:i',strtotime($v['time'])))
                ->setCellValue('H' . $i, $v['desc']);
            $i++;
        }
        //Set width
        /*$spreadsheet->getActiveSheet()
            ->getColumnDimension('A')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('B')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('C')
            ->setWidth(60);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('D')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('E')
            ->setWidth(20);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('F')
            ->setWidth(20);*/
        // Set alignment
        $spreadsheet->getActiveSheet()->getStyle('A1:F' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $spreadsheet->getActiveSheet()->getStyle('C2:C' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $spreadsheet->setActiveSheetIndex(0);
        ob_clean();
        header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
        header('content-type:application/octet-stream');
        header('Cache-Control: max-age=0');
        header("Content-Type:application/force-download");
        header("Content-Type:application/download");
        //header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . time() . microtime(true) . '.xlsx"');
        //header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);

        $writer->save('php://output');
        exit;
    }

    //账号充值
    public function money()
    {
        $id = input("id");

        if (request()->isAjax()) {

            $post = input('post.');

            if (!input('price')) {
                return ['err' => '充值金额不能为空'];
            }
            
            if (!input('content')) {
                //$post['content'] = '后台转账';
                return ['err' => '说明必填，且保证明确规范统一'];
            }
            $state = 0;
            if ($post['gateway'] == 1) {
                $state = Balance::index($id, $post['price'], $post['content'], $post['toward']);
            } elseif ($post['gateway'] == 3) {
                $state = Balance::index($id, $post['price'], $post['content'], $post['toward'], 1);
            } elseif ($post['gateway'] == 4) {
                $state = Balance::beans($id, $post['price'], $post['content'], $post['toward']);
            } else {
                $toward = $post['toward'] ? 0 : 1;
                $state = Income::index($id, 0, $post['price'], $post['content'], 1, '', $toward);
            }

            $admin = session('admin', '', 'mmjtAdmin');
            Db::name('admin_logs')->insert([
                'channel' => $post['gateway'],
                'toward' => $post['toward'],
                'money' => $post['price'],
                'admin' => $admin['name'],
                'user_id' => $id,
                'content' => $post['content']
            ]);

            $data = $state ? ['ret' => '成功'] : ['err'=>'操作失败或余额不足抵扣'];
            
        } else {
            if ($id) {
                $name = Db::name('user')->find($id);
                $this->assign('name', $name);
                $data = $this->fetch();
            } else {
                $data = ['err' => 'id参数错误'];
            }
        }
        return $data;
    }

    public function rengong()
    {
        $state = input('state');

        $map = [];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }


        if ($state !== null) {
            $map['t1.state'] = $state;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $date = input('date');
        if ($date) {
            $map['t1.time'] = ['like', '%' . $date . '%'];
        }

        $channel = input('channel') ?: 1;
        if ($channel) {
            $map['t1.channel'] = $channel;
        }
        $towardx = input('towardx'); //1增加 0扣减
        if ($towardx !== null) {
            $map['t1.toward'] = ['=',$towardx];
        }
        $map['t1.money'] = ['gt', 0];

        // 构建查询但不执行
        $query = Db::table('admin_logs')
            ->alias('t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($map)
            ->order('t1.time desc');

        // 执行查询并获取分页数据
        $data = $query->paginate(_getCachePages(), false, ['query' => request()->param()]);


        // 分别计算增加和扣除的总金额
        $increaseSum = Db::table('admin_logs t1')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($map)
            ->where('t1.toward', 1)
            ->sum('money');

        $decreaseSum = Db::table('admin_logs t1')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($map)
            ->where('t1.toward', 0)
            ->sum('money');

        // 组合金额信息
        if ($towardx !== null) {
            if($towardx==1){//增加
                $sumInfo = "增加总金额{$increaseSum}";
            }elseif($towardx==0){//扣减
                $sumInfo ="扣减总金额{$decreaseSum}";
            }
        }else{//全部
            $sumInfo = "增加总金额{$increaseSum}，扣减总金额{$decreaseSum}";
        }
        // 传递数据到视图
        $this->assign('sumInfo', $sumInfo);
        $this->assign('channel', $channel);
        $this->assign('towardx', $towardx);
        //$this->assign('month', $month);
        $this->assign('state', $state);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function rengongvip()
    {
        $map = [];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');

        if ($type == 1) {
            $map['t1.type'] = '0';
        } else if ($type == 2) {
            $map['t1.type'] = '1';
        } else if ($type == 3) {
            $map['t1.pay'] = '1';
        } else if ($type == 4) {
            $map['t1.pay'] = '2';
        } else if ($type == 5) {
            $map['t1.pay'] = '3';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $date = input('date');
        if ($date) {
            $map['t1.time'] = ['like', '%' . $date . '%'];
        }

        $map['t1.desc'] = ['like', '%后台添加'];

        $data = Db::table('vip_order')
            ->alias('t1')
            ->field('t1.*,t2.name, t3.name, t3.description')
            ->join('user t2', 't2.id = t1.user_id')
            ->join('vip_style t3', 't1.sid = t3.id')
            ->where($map)
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $sum = Db::table('vip_order t1')->join('user t2', 't2.id = t1.user_id')->where($map)->sum('price');

        $this->assign('sum', $sum);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    // =================  2020/10/29  ======================

    public function conditions()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $order = input('order') ? input('order') : 'asc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        $data = db('user_conditions')->where($where)->order('des ' . $order . ',id ' . $order)->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addconditions()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) { //添加数据
                unset($post['url']);
                $res = db('user_conditions')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据

                $res = db('user_conditions')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('user_conditions')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delconditions()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('user_conditions')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }



    public function yaoqingma()
    {
        $map = [];
        $revideo = input('revideo');

        if ($revideo !== null) {
            $map['type'] = $revideo;
        }
        $this->assign('revideo', $revideo);


        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('code')->where($map)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addyaoqingma()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$id) { //添加数据
                if (!$post['uid']) {
                    return ['err' => '用户ID不能为空'];
                }
                $res = Db::name('preach')->where('uid', $post['uid'])->where('state', 'in', '0,1')->select();
                if ($res) {
                    return ['err' => '用户已申请，待审核或已通过'];
                }

                $db = Db::name('preach')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {  //修改数据
                $post['updatetime'] = date('Y-m-d H:i:s');

                $db = Db::name('code')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('code')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delyaoqingma()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('code')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function codeinfo()
    {
        $code = input('code');
        if (request()->isAjax()) {
            $data = ['ret' => '修改成功'];
        } else {
            if ($code) {
                $name = Db::name('self_code')->where('code', $code)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function order()
    {
        $whereOr = $where = ['t1.status' => 1];

        $types = input('types');
        if ($types) {
            $whereOr['t1.types'] = $where['t1.types'] = $types;
        }

        $order = input('order', 'id');
        $this->assign('order', $order);

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if (stripos($search_name, ',') && $search_type == 'user_id') {
                $search_name = explode(',', $search_name);
                $where['t1.user_id']  = $search_name[0];
                $where['t1.data'] = ['like', '%'.$search_name[1].'%'];
                $whereOr['t1.user_id']  = $search_name[1];
                $whereOr['t1.data'] = ['like', '%'.$search_name[0].'%'];
            } else if ($search_type == 'toid') {
                $whereOr['t1.data'] = $where['t1.data'] = ['like', '%"touserid":"'.$search_name.'"%'];
            } else {
                $whereOr['t1.' . $search_type] = $where['t1.' . $search_type] = $search_name;
            }
        }
    
        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $whereOr['t1.create_time'] = $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $whereOr['t1.create_time'] = $where['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $whereOr['t1.create_time'] = $where['t1.create_time'] = ['elt', strtotime($end)];
        }

        $data = Db::name('order_common t1')
            ->field('t1.*, t2.name,t2.phone')
            ->join('user t2', 't2.id = t1.user_id', 'inner')
            ->where($where)->whereOr(function ($query) use ($whereOr) {
                $query->where($whereOr);
            })
            ->order('t1.'.$order.' desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function($item){
                if($item['types']==4){
                    $tmp = json_decode($item['data'],true);
                    $item['touserid'] = $tmp['touserid'] ?? 0;
                    $item['chatid'] = $tmp['id'];
                }else if($item['types']==2){
                    $tmp = json_decode($item['data'],true);
                    $item['touserid'] = $tmp['another_id'] ?? 0;
                }
                return $item;
            });

        $dataList = $data->all();
        $users = Db::name('user')->where(['id'=>['in', array_column($dataList, 'touserid')]])->column('id,name,sex','id');
        foreach ($dataList as &$value) {
            if (!isset($value['touserid'])) continue;
            $value['touser'] = $users[$value['touserid']]??false;
        }
    
        $sum = Db::name('order_common t1')
            ->join('user t2', 't2.id = t1.user_id', 'inner')
            ->where($where)->sum('t1.money');

        $this->assign('sum', round($sum, 2));
        $this->assign('types', $types);
    
        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('data', $dataList);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    public function delorder()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('order_common')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function balance()
    {
        $where = ['t1.id' => ['gt', 0]];
        
        $start = input('start');
        $end = input('end');
        $types = input('types');
        $content = input('content/s', '');
        
        if ($types !== null) {
            $where['types'] = $types;
        }
        $order = input('order/d', 1);
        $this->assign('order', $order);

        $ordersort = ['t1.id desc', 't1.time asc'];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t2.' . $search_type] = $search_name;
            if($search_type=='id'){
                $ids = explode(',', str_replace('，',',',$search_name));
                if(sizeof($ids) == 2){
                    $where['t1.content'] = ['like', '%('.$ids[1].')%'];
                }
            }
        }

        // if (!$search_name) {
        //     $start = $start ?: date('Y-m-d') . ' 00:00:00';
        // }


        if ($start && $end) {
            $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            $start_id = _day_first_id($start, 0, 'volley_desc', 'time', 'id');
            $end_id = _day_first_id(date('Y-m-d', strtotime($start))==date('Y-m-d', strtotime($end))?date('Y-m-d', strtotime($end)+86400):$end, $start_id, 'volley_desc', 'time', 'id');
            if ($end_id) {
                $where['t1.id'] = ['between', [$start_id, $end_id]];
            }
        } else if ($start && !$end) {
            $where['t1.time'] = ['egt', strtotime($start)];
            $start_id = _day_first_id($start, 0, 'volley_desc', 'time', 'id');
            if ($start_id) {
                $where['t1.id'] = ['egt', $start_id];
            }
        } else if (!$start && $end) {
            $where['t1.time'] = ['elt', strtotime($end)];
            $end_id = _day_first_id($end, 0, 'volley_desc', 'time', 'id');
            if ($end_id) {
                $where['t1.id'] = ['egt', $end_id];
            }
        }

        $type = input('type', 0);
        
        if ($type && sizeof($where) > 1) {
            if ($type == 1) {
                $where['t1.content'] = ['like', '%发消息扣金币'];
            }
            $this->assign('validtype', 1);
        }
        $this->assign('type', $type);

        if ($content) {
            $where['t1.content'] = ['like', "%$content%"];
        }


        $data = Db::name('volley_desc t1')
            ->field('t1.*,t2.name,t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)->order($ordersort[$order - 1])
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('types', $types);
        $this->assign('start', $start);
        $this->assign('end', $end);
        $this->assign('content', $content);

        return $this->fetch();
    }

    public function beauty()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('beauty_image')->where($where)->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addBeauty()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {

                $res = Db::name('beauty_image')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('beauty_image')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('beauty_image')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function delBeauty()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('beauty_image')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function tongji()
    {
        $data = Db::name('tongji_user')->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function tongjiProxy()
    {
        $date = input('date');

        $data = Db::name('tongji_proxy t1')
            ->field('t1.*, t2.name, t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where(['t1.date' => $date])
            ->order('t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function chat()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $types = input('types');
        if ($types) {
            $where['types'] = $types;
        }

        $data = Db::name('config_price')->where($where)->order('price asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('types', $types);

        return $this->fetch();
    }

    public function addChat()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {

                $res = Db::name('config_price')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('config_price')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('config_price')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function delChat()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('config_price')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
    
    
        public  function look_idcards(){
        $id= input('id',0);
        $total = 10;
        $userInfo = $this->adminInfo;

        $lookInfo = Db::name('look_idcard_times')->where(['card_id'=>$id,'admin_id'=>$userInfo['id']])->find();
        if ($lookInfo){
            if($lookInfo['num']<=$total){
                Db::name('look_idcard_times')->where(['id'=>$lookInfo['id']])->update(['num'=>$lookInfo['num']+1]);
            }
            $times = $lookInfo['num'];
        }else{
            if ($userInfo['type'] !=1){
                $add_data = [
                    'card_id'=>$id,
                    'admin_id'=>$userInfo['id'],
                    'num'=>1,
                ];
                Db::name('look_idcard_times')->insert($add_data);
            }
            $times = 1;
        }
        return json_encode(['code'=>200,'msg'=>'成功','data'=>['total'=>$total,'have_use'=>$times,'id'=>$id,'user_id'=>$userInfo['id'],'type'=>$userInfo['type']]]);
    }
    
    
    public function certification()
    {
        $where = [];
        $whereRaw = '';

        $types = input('types') ?: 1;
        if ($types) {
            $where['t1.types'] = $types;
        }

        $status = input('status');
        if ($status !== null) {
            $where['t1.status'] = $status;
        }

        $longname = input('longname/d', 0);
        $this->assign('longname', $longname);
        if ($longname && $types == 1) {
            $whereRaw = 'CHAR_LENGTH(t1.data2) > 3';
        }


        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if($search_type == 'data'){
                $where['t1.' . $search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t2.' . $search_type] = $search_name;
            }
        }

        $data = Db::name('user_certification t1')
            ->master(true)
            ->field('t1.*, t2.name,t2.phone,t2.sex,t2.age,t2.city,t2.province,t2.education_background, t2.emotion,t2.is_house_purchase,t2.monthly_salary,t2.is_car_purchase')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->where($whereRaw)
            ->order('t1.create_time desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function($item) use ($types){
                if($types == 1){
                    $item['authpic'] = Db::name('auth')->where(['user_id'=>$item['user_id']])->value('image1');
                }
                if (($item['create_time']+172800) <time()  && $this->adminInfo['type'] !=1){
                    $item['data'] = substr_replace($item['data'],'****',-4,4);
                }
                return $item;
            });
        $nothead = input('nothead/d', 0);
        $this->assign('nothead', $nothead);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('types', $types);
        $this->assign('status', $status);

        return $this->fetch();
    }

    public function certificationWatch($id)
    {
        $name = Db::name('user_certification')->find($id);

        if ($name) {
            $name['reason_records'] = Db::name('user_certification_reject')->where(['user_id'=>$name['user_id']])->select();
            $admins = Db::name('admin')->column('name','id');
            foreach ($name['reason_records'] as &$value) {
                $value['admin_name'] = $admins[$value['admin_id']] ?? $value['admin_id'];
            }
        }

        $this->assign('name', $name);
        return $this->fetch();
    }

    public function certificationEdit()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');
            $timenow = time();
            $admin = session('admin', '', 'mmjtAdmin');
            if ($id) {
                $update = ['status' => $post['status'], 'reason' => input('reason',''), 'update_time' => $timenow, 'shenhe_time'=>time(), 'shenhe_admin_id'=>$this->adminInfo['id']];
                $certification = Db::name('user_certification')->find($id);
                $user = Db::name('user')->where(['id' => $certification['user_id']])->find();
                if ($post['status'] == -1) {
                    $status = 3;
                    Db::name('user_certification_reject')->insert([
                        'user_id'=>$certification['user_id'],
                        'admin_id'=>$admin['id'],
                        'time'=>$timenow,
                        'reason'=>$post['reason']
                    ]);
                } else if ($post['status'] == 0) {
                    $status = 1;
                } else if ($post['status'] == 1) {
                    $status = 2;
                }

                // if ($certification['status'] == 1) {
                //     $admin = Session::get('admin', 'mmjtAdmin');
                //     if ($admin['type'] != 1) {
                //         return ['err' => '当前账户无权修改，请联系总后台'];
                //     }
                // }

                $contain = ['', 'realname_auth', 'is_education_authentication', 'car_auth', 'house_auth', 'voice_auth', 'income_auth', 'marry_auth'];
                $msg = ['', '实名认证', '学历认证', '车辆认证', '房产认证', '语音签名', '收入认证', '婚姻证明'];
                $types = [1 => 'name_auth', 2 => 'education_auth', 3 => 'car_auth', 4 => 'house_auth', 5 => 'voice', 6 => 'income_auth', 7 => 'marry_auth'];
                $where = [$contain[$certification['types']] => $status];

                Db::name('user')->where(['id' => $certification['user_id']])->update($where);

                $result = Db::name('user_certification')->where('id', $id)->update($update);


                if (in_array($post['status'], [-1,1])) {
                    if ($post['status'] == -1) {
                        $content = $msg[$certification['types']] . '未通过，请重新提交。原因:' . input('reason');
                    } else {
                        if ($certification['types'] == 5) {
                            Db::name('user')->where(['id' => $certification['user_id']])->update(['voice' => $certification['image_front']]);
                        } else if ($certification['types'] == 1) {
                            $realbirthDay = _getDateFromIdcard($certification['data']);
                            $realAge = countage($realbirthDay);
                            $setAge = $user['age'];
                            if ($setAge > $realAge + 5 || $realAge - 5 > $setAge) {
                                $maxDec = $realAge - 5 > 18 ? -5 : 18 - $realAge;
                                $maxDec = $maxDec > 0 ? '+'.$maxDec.' year' : '-'.$maxDec.' year';
                                $setBirthday = date('Y-m-d', strtotime($maxDec, strtotime($realbirthDay)));
                                $setAge = countage($setBirthday);
                                Db::name('user')->where(['id'=>$certification['user_id']])->update(['age'=>$setAge, 'birthday'=>$setBirthday]);
                            }
                            PrivatechatGreet::initOne($user);
                            Db::name('user')->where(['id' => $certification['user_id'], 'quality' => 3])->update(['quality' => 4]);
                        }

                        $content = '你的'.$msg[$certification['types']] . '已通过。';

                        // 任务
                        Task::finish($types[$certification['types']], $certification['user_id']);
                    }

                    Privatechat::notice($certification['user_id'], $content);
                }

                $data = $result ? ['ret' => '修改成功'] : ['err' => '修改失败'];
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    public function certificationDel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $res = Db::name('user_certification')->where(['id' => $id])->find();
                $db = Db::name('user_certification')->delete($id);
                if ($db) {
                    if($res['types'] == 1){
                        Db::name('user')->where(['id'=>$res['user_id']])->update(['realname_auth'=>0]);
                    }
                    $images = $imagesa = $imagesb = [];
                    if($res['image_front']){
                        $imagesa = explode(',', $res['image_front']);
                    }
                    if($res['image_behind']){
                        $imagesb = explode(',', $res['image_behind']);
                    }
                    $images = array_unique(array_merge($imagesa, $imagesb));
                    foreach ($images as $key => $value) {
                        \app\service\AliOss::delete($value);
                    }
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
    public function certificationReject()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                
                if ($search_type == 'id'){
                    $where['user_id'] = ['like', '%'.$search_name.'%'];
                }else{
                    $where[$search_type] = $search_name;
                }
                // $where[$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where[$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where[$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('user_certification_reject')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $dataList = $data->all();
        $user = Db::name('user')->where(['id'=>['in', array_column($dataList, 'user_id')]])->column('name', 'id');
        $admin = Db::name('admin')->column('name', 'id');
        foreach ($dataList as &$value) {
            $value['name'] = $user[$value['user_id']] ?? '';
            $value['admin_name'] = $admin[$value['admin_id']] ?? '';
        }

        $this->assign('data', $dataList);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function authadd()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if ($id) {
                $photo = Db::name('user_img')->find($id);
                
                if ($photo) {
                    $contain = ['status' => $post['shenhe'], 'shenhe_time'=>time(), 'shenhe_admin_id'=>$this->adminInfo['id']];
    
                    if ($photo['types'] == 1 && $photo['burn'] == 0 && $photo['packet'] == 0 && $post['shenhe'] == 1) {
                        $image = json_decode($photo['pic'], true)[0];
                        
                        $where = ['type' => 4, 'userid' => $photo['user_id']];
                        if ($photo['join_dynamic']) {
                            $where['dy_id'] = $photo['join_dynamic'];
                        } else {
                            $similar = Db::name('user_img')->where([
                                'types' => 1,
                                'user_id' => $photo['user_id'],
                                'burn' => 0,
                                'packet' => 0,
                                'status' => 1,
                                'remark' => $photo['remark']
                            ])->find($id);
                            
                            if ($similar && $similar['join_dynamic']) {
                                $where['dy_id'] = $similar['join_dynamic'];
                            }
                        }
                        $dynamic = Db::name('dymanic')->where($where)->find();
                        
                        if (isset($where['dy_id']) && $dynamic) {
                            $sumbImage = $dynamic['sumbImage'] . ',' . $image;
                            $masterimg = $dynamic['masterimg'] . ',' . $image;
    
                            Db::name('dymanic')->where(['dy_id' => $dynamic['dy_id']])->update(['sumbImage' => $sumbImage, 'masterimg' => $masterimg]);
                        } else {
                            /*$city = Db::name('user')->where(['id' => $photo['user_id']])->value('city');
    
                            $dynamic_id = Db::name('dymanic')->insertGetId([
                                'type' => 4,
                                'userid' => $photo['user_id'],
                                'sumbImage' => $image,
                                'masterimg' => $image,
                                'citys' => $city ?: '',
                                'shenhe_time' => time(),
                            ]);
    
                            $contain['join_dynamic'] = $dynamic_id;*/
                        }
                    }
    
                    $db = Db::name('user_img')->where('id', $id)->update($contain);
    
                    Cache::rm('photos' . $photo['user_id']);
                    Cache::rm('photosCount' . $photo['user_id']);
                } else {
                    return ['err' => '照片不存在'];
                }
                
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    public function imglistshenheAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $status = input('status');
            $time = time();
            foreach ($_POST['delAll'] as $v) {

                $photo = Db::name('user_img')->find($v);
                
                if ($photo) {
                    $contain = ['status' => $status, 'shenhe_time'=>$time, 'shenhe_admin_id'=>$this->adminInfo['id']];
    
                    if ($photo['types'] == 1 && $photo['burn'] == 0 && $photo['packet'] == 0 && $status == 1) {
                        $image = json_decode($photo['pic'], true)[0];
                        
                        $where = ['type' => 4, 'userid' => $photo['user_id']];
                        if ($photo['join_dynamic']) {
                            $where['dy_id'] = $photo['join_dynamic'];
                        } else {
                            $similar = Db::name('user_img')->where([
                                'types' => 1,
                                'user_id' => $photo['user_id'],
                                'burn' => 0,
                                'packet' => 0,
                                'status' => 1,
                                'remark' => $photo['remark']
                            ])->find($v);
                            
                            if ($similar && $similar['join_dynamic']) {
                                $where['dy_id'] = $similar['join_dynamic'];
                            }
                        }
                        $dynamic = Db::name('dymanic')->where($where)->find();
                        
                        if (isset($where['dy_id']) && $dynamic) {
                            $sumbImage = $dynamic['sumbImage'] . ',' . $image;
                            $masterimg = $dynamic['masterimg'] . ',' . $image;
    
                            Db::name('dymanic')->where(['dy_id' => $dynamic['dy_id']])->update(['sumbImage' => $sumbImage, 'masterimg' => $masterimg]);
                        }
                    }
    
                    $db = Db::name('user_img')->where('id', $v)->update($contain);
    
                    Cache::rm('photos' . $photo['user_id']);
                    Cache::rm('photosCount' . $photo['user_id']);
                }
            }
            $data = ['ret' => '更新成功'];
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    public function detail()
    {
        $id = input("id");

        if (request()->isAjax()) {

        } else {
            if ($id) {
                $name = Db::name('withdraw')->find($id);

                if ($name) {
                    $name['data'] = json_decode($name['data'], true);

                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function exchange()
    {
        $data = Db::name('exchange_style')->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addExchange()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$id) {
                $db = Db::name('exchange_style')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $db = Db::name('exchange_style')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('exchange_style')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delExchange()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('exchange_style')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function exportData()
    {
        $post = input('')['delAll'];
        $sex = input('sex');

        $time_type = input('time_type', 'register_datetime');
        $datemin = input('datemin', '');
        $datemax = input('datemax', '');
        if ($time_type == 'last_login_time') {
            $datemin = $datemin?strtotime($datemin):'';
            $datemax = $datemax?strtotime($datemax):'';
        }
        $quality = input('quality');
        $recharge = input('recharge');
        $sort = input('sort', 0);
        $orders = ['id desc', 'register_datetime desc', 'volley desc', 'score desc', 'last_login_datetime asc'];
        $order = $orders[$sort];

        if ($post || $sex || $datemin || $datemax) {
            if ($sex) {
                $sex = $sex == 1 ? '男' : '女';
                $map = ['sex' => $sex];
                if ($quality) {
                    $map['quality'] = $quality;
                }
                if ($datemin) {
                    if ($datemax) {
                        $map[$time_type] = ['between', [$datemin, $datemax]];
                    } else {
                        $map[$time_type] = ['>=', $datemin];
                    }
                } else if ($datemax) {
                    $map[$time_type] = ['<=', $datemax];
                }

                $result = Db::name('user')->field('id, name, sex, phone, volley, score, register_datetime, yqr')->where($map)->order($order)->select();
                if ($recharge) {
                    $alluids = array_column($result, 'id');
                    $uids = [];
                    $overuids = Db::name('user_data')->where(['user_id'=>['in', $alluids], 'topup'=>['>=', 5000]])->column('user_id');
                    $result = array_diff($alluids, $overuids);
                    foreach ($alluids as &$value) {
                        $val = UserIntimate::TopupCount($value);
                        if ($val['topup'] < 5000) {
                            $uids[] = $value;
                        }
                    }
                    $map['id'] = ['in', $uids];
                    $result = Db::name('user')->field('id, name, sex, phone, volley, score, register_datetime, yqr')->where($map)->order($order)->select();
                }
            } else if ($post) {
                $where = ['id' => ['in', $post]];
                $result = Db::name('user')->field('id, name, sex, phone, volley, score, register_datetime, yqr')->where($where)->order($order)->select();
            } else {
                if ($datemin) {
                    if ($datemax) {
                        $where[$time_type] = ['between', [$datemin, $datemax]];
                    } else {
                        $where[$time_type] = ['>=', $datemin];
                    }
                } else if ($datemax) {
                    $where[$time_type] = ['<=', $datemax];
                }
                $result = Db::name('user')->field('id, name, sex, phone, volley, score, register_datetime, yqr')->where($where)->order($order)->select();
            }

            $users = Db::name('user')->where(['yqm' => ['in', array_unique(array_filter(array_column($result, 'yqr')))]])->column('id','yqm');
            $userData = Db::name('user_data')->where(['user_id'=>['in',array_column($result, 'id')]])->column('topup,income,consume','user_id');
            $userCert = Db::name('user_certification')->where(['user_id'=>['in',array_column($result, 'id')]])->column('data,data2','user_id');
            foreach ($result as $key => $value) {
                $result[$key]['topup'] = isset($userData[$value['id']]) ? floatval($userData[$value['id']]['topup']) : 0;
                $result[$key]['income'] = isset($userData[$value['id']]) ? floatval($userData[$value['id']]['income']) : 0;
                $result[$key]['consume'] = isset($userData[$value['id']]) ? floatval($userData[$value['id']]['consume']) : 0;
                $result[$key]['yqr'] = isset($users[$value['yqr']]) ? $users[$value['yqr']] : '';
                $result[$key]['idcard'] = isset($userCert[$value['id']]) ? $userCert[$value['id']]['data'] : '';
                $result[$key]['realname'] = isset($userCert[$value['id']]) ? $userCert[$value['id']]['data2'] : '';
            }
            // echo "<pre>";
            // var_dump($result);exit;
            if ($result) {
                $this->installUsers($result);
            }

            $data = ['ret' => '成功'];
        } else {
            $data = ['err' => '失败，未选中数据'];
        }
        return $data;
    }

    public function installUsers($data)
    {
        $spreadsheet = new Spreadsheet();

        // Add title
        $spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '昵称')
            ->setCellValue('C1', '性别')
            ->setCellValue('D1', '手机')
            ->setCellValue('E1', '金币')
            ->setCellValue('F1', '积分')
            ->setCellValue('G1', '总充值')
            ->setCellValue('H1', '总消费')
            ->setCellValue('I1', '总收益')
            ->setCellValue('J1', '注册时间')
            ->setCellValue('K1', '邀请人ID')
            ->setCellValue('L1', '实名')
            ->setCellValue('M1', '身份证');

        // Rename worksheet
        $spreadsheet->getActiveSheet()->setTitle('用户');
        $i = 2;
        foreach ($data as $v) {
            // Add data
            $spreadsheet->getActiveSheet()
                ->setCellValue('A' . $i, $v['id'])
                ->setCellValue('B' . $i, $v['name'] . "\t")
                ->setCellValue('C' . $i, $v['sex'] . "\t")
                ->setCellValue('D' . $i, $v['phone'] . "\t")
                ->setCellValue('E' . $i, $v['volley'])
                ->setCellValue('F' . $i, $v['score'])
                ->setCellValue('G' . $i, $v['topup'])
                ->setCellValue('H' . $i, $v['consume'])
                ->setCellValue('I' . $i, $v['income'])
                ->setCellValue('J' . $i, $v['register_datetime'] . "\t")
                ->setCellValue('K' . $i, $v['yqr'] . "\t")
                ->setCellValue('L' . $i, $v['realname'] . "\t")
                ->setCellValue('M' . $i, $v['idcard'] . "\t");
            $i++;
        }

        // Set alignment
        $spreadsheet->getActiveSheet()->getStyle('A1:F' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $spreadsheet->getActiveSheet()->getStyle('C2:C' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $spreadsheet->setActiveSheetIndex(0);

        ob_clean();
        header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
        header('content-type:application/octet-stream');
        header('Cache-Control: max-age=0');
        header("Content-Type:application/force-download");
        header("Content-Type:application/download");
        header('Content-Disposition: attachment;filename="' . time() . microtime(true) . '.xlsx"');

        $writer = new Xlsx($spreadsheet);

        $writer->save('php://output');

        exit;
    }

    public function exportPhoneData()
    {
        $post = input('')['delAll'];
        $sex = input('sex');
        $datemin = input('datemin');
        $datemax = input('datemax');
        $timekey = input('timekey');
        $logintime = input('logintime', 0);
        $order = $logintime ? 'last_login_datetime asc' : '';
        $phone = [];
        if ($post){
            $phone = Db::name('user')->where(['id'=>['in', $post]])->whereNotNull('phone')->order($order)->column('phone');
        } else if ($datemax || $datemin) {
            $where = [];
            if ($datemin) {
                if ($datemax) {
                    $where[$timekey] = ['between', [$datemin, $datemax]];
                } else {
                    $where[$timekey] = ['>=', $datemin];
                }
            } else if ($datemax) {
                $where[$timekey] = ['<=', $datemax];
            }
            if ($sex) {
                $where['sex'] = $sex;
            }
            $phone = Db::name('user')->where($where)->whereNotNull('phone')->order($order)->column('phone');
        }

        $time = time();
        $content = implode("\r\n",$phone);
        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Content-Disposition: attachment;filename = $time.txt");//文件命名
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: public");
        echo $content;
    }

    
    public function inviteCode($id, $prev_id)
    {
        $prev_id_old = $prev_id;
        $prev_id = intval($prev_id);
    
        if ($prev_id == $id) {
            return ['err' => '不能绑定自己'];
        }
        
        $user = Db::name('user')->find($id);
    
        if (!$user) {
            return ['err' => '用户不存在'];
        }
        
        $adminInfo = $this->adminInfo;
        // if ($adminInfo['name'] !='admin' &&  $adminInfo['name'] != 'kefu01'  && $adminInfo['name'] != 'kefu02'){
        //     if ($user['yqr']) {
        //         return ['err' => '邀请人已存在'];
        //     }
        // }
        
        if (!$prev_id && $prev_id_old == '' && $user['yqr']) {
            User::bindParent('', $user['id'], 3, $this->adminInfo['id'], 0);
            Db::name('user')->where(['id' => $id])->setField('yqr', '');
            return ['ret' => '解绑成功'];
        }
    
        $parent = Db::name('user')->where(['id' => $prev_id])->find();
    
        if (!$prev_id && $prev_id_old && $user['yqr']) {
            if (!$user['invite_time']) {
                Db::name('user')->where(['id' => $id])->update(['invite_time' => time()]);
            }
            return ['ret' => '绑定成功'];
        }
    
        if (!$parent) {
            return ['err' => '邀请人不存在'];
        }
        
        if ($this->ischild($parent['yqm'], $user['yqm'])) {
            return ['err' => '不能绑定下两级'];
        }

        $update = ['yqr' => $parent['yqm'], 'invite_time' => time()];
        if ($user['entertainment'] == 1) {
            $update['entertainment'] = $parent['entertainment'];
        }
        User::bindParent($parent['id'], $user['id'], 3, $this->adminInfo['id']);
        Db::name('user')->where(['id' => $id])->update($update);

        if ($user['yqr'] != $parent['yqm']) {
            Reg::parentSay($id, $user['sex'], $parent['yqm']);
            User::bindParentWalfare($parent['id'], $user['id'], $user['device_id']);
        }

    
        return ['ret' => '绑定成功'];
    }
    
    //新的后台绑定函数
    public function inviteCode_new($id, $prev_id)
    {
        // 参数预处理
        $prev_id_old = $prev_id;//传递的原始邀请邀请人id（可能是字符串）
        $prev_id = intval($prev_id);
        $adminId = $this->adminInfo['id'];

        // 基础校验
        if ($prev_id == $id) {
            return ['err' => '不能绑定自己'];
        }

        // 获取用户信息
        $users = Db::name('user')
            ->where('id', 'in', [$id, $prev_id])
            ->column('*', 'id');

        $user = $users[$id] ?? [];
        if (empty($user)) {
            return ['err' => '用户不存在'];
        }

        // 权限检查
        $adminName = $this->adminInfo['name'];
        // $isPrivileged = in_array($adminName, ['admin', 'kefu01', 'kefu02']);

        // if (!$isPrivileged && !empty($user['yqr'])) {
        //     return ['err' => '邀请人已存在，无权限修改'];
        // }

        // 开启事务
        Db::startTrans();
        try {
            // 解绑逻辑
            if (!$prev_id && $prev_id_old === '' && !empty($user['yqr'])) {
                User::bindParent('', $user['id'], 3, $adminId, 0); // 解绑操作
                Db::name('user')->where('id', $id)->setField('yqr', '');
                Db::commit();
                return ['ret' => '解绑成功'];
            }

            // 绑定逻辑
            $parent = $users[$prev_id] ?? [];
            if (empty($parent)) {
                return ['err' => '邀请人不存在'];
            }

            // 层级校验（防止循环绑定）
            if ($this->ischild($parent['yqm'], $user['yqm'])) {
                return ['err' => '不能绑定下两级'];
            }

            // 更新用户信息
            $updateData = [
                'yqr' => $parent['yqm'],
                'invite_time' => time()
            ];

            if ($user['entertainment'] == 1) {
                $updateData['entertainment'] = $parent['entertainment'];
            }

            // 执行绑定并触发奖励计算
            if(empty($user['yqr'])){//之前没有邀请人的话进行绑定前充值（金币充值、会员充值金额补发）
                User::bindParent_new($parent['id'], $user['id'], 3, $adminId,1,'管理后台绑定');
            }
            Db::name('user')->where('id', $id)->update($updateData);

            // 发送通知（仅当邀请码确实发生变更时）
            if ($user['yqr'] != $parent['yqm']) {
                Reg::parentSay($id, $user['sex'], $parent['yqm']);
            }

            Db::commit();
            return ['ret' => '绑定成功'];
        } catch (\Exception $e) {
            Db::rollback();
            // 记录系统错误日志
            Log::error('邀请绑定失败：' . $e->getMessage(), [
                'user_id' => $id,
                'parent_id' => $prev_id,
                'admin_id' => $adminId
            ]);
            return ['err' => '系统错误，请稍后重试'];
        }
    }
    
    // 是否为下两级用户
    public function ischild($yqm, $yqr)
    {
        $next1 = Db::name('user')->where(['yqr'=>$yqm])->column('yqm');
        if(sizeof($next1) == 0){
            return false;
        }
        $next2 = Db::name('user')->where(['yqr'=>['in', $next1]])->column('yqm');
        $next = array_merge($next1, $next2);
        return in_array($yqr, $next);
    }


    public function ordernotify220719()
    {
        $out_trade_no = input('no');
        OrderCommon::notify($out_trade_no);
    }














    //会员管理
    public function images()
    {
        $where = ['user.id' => ['gt', 0]];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $where['city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');
        if ($type == 1) {
            $where['vip_end_datetime'] = ['egt', date('Y-m-d H:i:s')];
        } else if ($type == 2) {
            $where['is_identity_authentication'] = '2';
            $where['sex'] = "女";
        } else if ($type == 3) {
            $where['register_datetime'] = ['egt', date('Y-m-d')];
        }

        $order = 'user.sort desc, user.id desc';
    

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if (in_array($search_type, ['id', 'yqr'])) {
                $where['user.'.$search_type] = $search_name;
            } else if ($search_type == 'device_id' && $search_name) {
                $recycle_userids = Db::name('recycle_user')->where(['data' => ['like', '%'.$search_name.'%']])->column('user_id');
                $unzhuxiao_userids = Db::name('user')->where(['device_id' => $search_name])->column('id');
                $where['user.id'] = ['in', array_merge($recycle_userids,$unzhuxiao_userids)];
            } else if ($search_type == 'cluster') {
                $ids = Db::name('cluster_user')->where(['cluster_id' => $search_name])->column('user_id');

                if ($ids) {
                    $where['user.id'] = ['in', $ids];
                } else {
                    $where['user.id'] = 0;
                }
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $date = input('date');
        if ($date) {
            $where['register_datetime'] = ['like', '%' . $date . '%'];
        }

        $data = Db::name('user')->join('user_img', 'user_img.user_id=user.id')->where($where)->group('user.id')->order($order)->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function($item, $key){
            $imagelists = Db::name('user_img')->where('user_id', $item['id'])->order('id desc')->select();
            $item['imagelists'] = [];
            foreach ($imagelists as $key => $value) {
                $item['imagelists'] = array_merge($item['imagelists'],json_decode($value['pic'], true));
                $item['imagelists'] = array_unique($item['imagelists']);
            }

            return $item;
        });




        $this->assign('admin', $admin);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }





    public function topuplimit()
    {
        if (request()->isAjax()) {
            $admin = session('admin', '', 'mmjtAdmin');
            if ($admin['type'] != 1) {
                return ['err' => '无权限'];
            }
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $res = false;
            $time = time();
            $result = false;
            if ($user) {
                $topuplimit = Db::name('topup_limit')->where(['user_id'=>$post['user_id']])->find();
                if($topuplimit){
                    $topuplimited = $topuplimit['value'];
                    $topuplimitid = $topuplimit['id'];
                }else{
                    $topuplimited = 0;
                    $topuplimitid = Db::name('topup_limit')->insertGetid(['user_id'=>$post['user_id'], 'time' => $time]);
                }
                if($post['value'] >= 0){
                    if ($post['value'] > 5000) {
                        return ['state' => 0, 'msg' => '充值限额当前可填写金额最大为 5000'];
                    }
                    $res = Db::name('topup_limit')->where(['id'=>$topuplimitid])->update(['value'=>$post['value'], 'time' => $time]);
                }else{
                    $result = ['state' => 0, 'msg' => '错误值'];
                }
            }

            if ($res !== false) {
                $result = ['state' => 1, 'msg' => '操作成功'];
            } elseif(!$result) {
                $result = ['state' => 0, 'msg' => '操作失败'];
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            $where['t1.value'] = ['>', 0];
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('topup_limit')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }
    
    public function untopuplimit()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            $value = input('value',0);
            $remark = input('remark','');
            $res = Db::name('topup_limit')->where('id', $id)->find();
            $data = ['err' => '设置失败'];
            if(is_numeric($value)){
                if ($res && $value >= 0) {
            if ($value > 5000) {
                return ['err' => '充值限额当前可填写金额最大为 5000'];
            }
                    Db::name('topup_limit')->where('id', $id)->update(['value'=>$value]);
                    $data = ['ret' => '设置成功'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('topup_limit')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function idcardenter()
    {
        $id = input('id');
        $data = input('data','');
        if(!validateIDCard($data)){
            return ['err'=>'错误的身份证号码'];
        }
        $has = Db::name('user_certification')->where(['data'=>$data, 'id'=>['neq', $id]])->find();
        $admin = Session::get('admin', 'mmjtAdmin');
        // if ($admin['type'] == 1) {
        //     $has = false;
        // }
        if($has){
            $data = ['err' => '身份证已存在'];
        }else{
            $certification = Db::name('user_certification')->where(['id'=>$id])->find();

            if ($certification['data']) {
                return ['err' => '当前禁止修改身份证号'];
            }

            if ($certification['status'] == 1 && $certification['data']) {
                if ($admin['type'] != 1) {
                    return ['err' => '当前账户无权修改，请联系总后台'];
                }
            }
            $res = Db::name('user_certification')->where(['id'=>$id])->update(['data'=>$data]);
            if($res){
                $data = ['ret' => '身份证验证成功'];
            }else{
                $data = ['err' => '修改失败'];
            }
        }
        return $data;
    }
    public function idcardnameenter()
    {
        $id = input('id');
        $data = input('data','');
        $res = Db::name('user_certification')->where(['id'=>$id])->update(['data2'=>$data]);
        if($res){
            $data = ['ret' => '修改成功'];
        }else{
            $data = ['err' => '修改失败'];
        }
        return $data;
    }




    public function recyclereview()
    {
        $map = [];
        $state = input('state/d', 0);
        $map['a.state'] = $state;
        $this->assign('state', $state);


        $search_name = input('param.name');
        $search_type = input('param.type');
        $this->assign('search_name', $search_name);
        $this->assign('search_type', $search_type);
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $map['b.' . $search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $map['b.' . $search_type] = ['like', '%' . $search_name . '%'];
            }else{
                $map['a.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = Db::name('recycle_review')
                    ->alias('a')
                    ->join('user b', 'a.user_id=b.id')
                    ->where($map)
                    ->order('a.id desc')
                    ->field('a.id as rid, a.create_time, a.update_time, a.state, a.remark, b.*')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()])
                    ->each(function ($item){

                        // $item['topup_sum'] = 0;
                        // $item['withdraw_sum'] = 0;

                        // return $item;
                        $item['device_account_count'] = 1;
                        $uni_userids_in_a = [];
                        $uni_userids_in_b = [];
                        $uni_userids_in_c = [];
                        $where_1 = [];
                        $where_2 = [];
                        if($item['device_id']){
                            $where_1[] = "data like '%".$item['device_id']."'";
                            $where_2[] = "device_id = '".$item['device_id']."'";
                        }
                        if($item['zhifucount']){
                            $where_1[] = "data like '%".$item['zhifucount']."'";
                            $where_2[] = "zhifucount = '".$item['zhifucount']."'";
                        }
                        if($item['zhifuname']){
                            $where_1[] = "data like '%".$item['zhifuname']."'";
                            $where_2[] = "zhifuname = '".$item['zhifuname']."'";
                        }
                        if($item['phone']){
                            $where_1[] = "phone = '".$item['phone']."'";
                        }
                        if (sizeof($where_1)) {
                            $uni_userids_in_a = Db::name('recycle_user')->where(implode(' and ', $where_1))->column('user_id');
                        }
                        if (sizeof($where_2)) {
                            $uni_userids_in_b = Db::name('user')->where(implode(' and ', $where_2))->column('id');
                        }


                        $where_3 = [];
                        $whereUDevs = [];
                        $historyData = Db::name('user_repeat_check')->find($item['id']);
                        if($historyData){
                            if($historyData['device_ids']){
                                $tmp = explode(',', $historyData['device_ids']);
                                foreach ($tmp as $key => $value) {
                                    // $where_3[] = "device_ids like '%".$value."'";
                                    $whereUDevs[] = $value;
                                }
                            }
                            if($historyData['zhifucounts']){
                                $tmp = explode(',', $historyData['zhifucounts']);
                                foreach ($tmp as $key => $value) {
                                    $where_3[] = "zhifucounts like '%".$value."'";
                                }
                            }
                        }
                        if (sizeof($where_3)) {
                            $uni_userids_in_c = Db::name('user_repeat_check')->master()->where(implode(' and ', $where_3))->column('user_id');
                        }
                        if (sizeof($whereUDevs)) {
                            $uni_userids_in_c = Db::name('user_device_records')->master()->where(['device_id'=>['in',$whereUDevs]])->group('user_id')->column('user_id');
                        }

                        $all_uids = array_unique(array_merge($uni_userids_in_a, $uni_userids_in_b, $uni_userids_in_c));
                        $item['device_account_count'] = sizeof($all_uids);
                        $item['device_account_count'] = $item['device_account_count'] ? $item['device_account_count'] : 1;


                        $item['topup_sum'] = 0;
                        $item['withdraw_sum'] = 0;

                        if($item['device_account_count'] > 1){
                            $withdrawdata = [];
                            foreach ($all_uids as $uid) {
                                $userData = Db::name('user_data')->where(['user_id' => $uid])->find();
                                $item['topup_sum'] += $userData ? $userData['topup'] : 0;
                                $wdata = Db::name('withdraw')->where(['userid'=>$uid, 'state'=>['in', [0,1]]])->find();
                                if($wdata){
                                    $wdata = json_decode($wdata['data'], true);
                                    if(!in_array($wdata['account'], $withdrawdata)){
                                        $withdrawdata[] = $wdata['account'];
                                    }
                                }
                            }
                            foreach ($withdrawdata as $wdataitem) {
                                $item['withdraw_sum'] += Db::name('withdraw')->where(['data' => ['like', '%'.$wdataitem.'%'], 'state' => ['in', [0,1]]])->sum('money');
                            }
                        }else{
                            $item['withdraw_sum'] = Db::name('withdraw')->where(['userid' => $item['id'], 'state' => ['in', [0,1]]])->sum('money');
                            $userData = Db::name('user_data')->where(['user_id' => $item['id']])->find();
                            $item['topup_sum'] = $userData ? $userData['topup'] : 0;
                        }
                        return $item;
                    });
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }



    public function recycleedit()
    {
        $id = input('id');
        $admin = Session::get('admin', 'mmjtAdmin');
        $name = Db::name('recycle_review')->where(['id'=>$id, 'state'=>0])->find();
        $user = Db::name('user')->where(['id'=>$name['user_id']])->find();
        if (request()->isAjax()) {
            $post = input('post.');
            $time = time();
            $status = false;
            Db::startTrans();
            try{
                if ($post['state'] == 1) {
                    Db::name('recycle_user')->insert([
                        'channel' => 1,
                        'user_id' => $name['user_id'],
                        'phone' => $user['phone']??'',
                        'data' => json_encode($user),
                        'ip' => $name['ip'],
                        'os' => $name['os'],
                        'create_time' => $time,
                    ]);
                    $update = [
                        'id' => $name['user_id'],
                        //'name' => '已注销',
                        //'phone'=>null,
                        'wechat'=>null,
                        'qq_openID'=>null,
                        'delete_time' => $time
                    ];
                    User::update($update);
                    Db::name('user_auth')->where(['user_id'=>$name['user_id']])->update(['state'=>0]);
                    Db::name('chat_lists')->where(['user_id'=>$name['user_id']])->update(['another_unread'=>0]);
                    Db::name('chat_lists')->where(['another_id'=>$name['user_id']])->update(['user_unread'=>0]);
                    (new \app\service\TencentIM)->account_delete($name['user_id']);
                }

                $post['update_time'] = $time;
                $post['admin_id'] = $admin['id'];

                $db = Db::name('recycle_review')->where('id', $id)->update($post);
                Db::commit();
                $data = ['ret' => '修改成功'];
                $status = true;
            } catch(\Exception $e){
                Db::rollback();
                $data = ['err' => '修改失败'];
            }
            if($post['state'] == -1 && $status){
                Privatechat::notice($name['user_id'], '注销申请被驳回，驳回原因：' . $post['remark']);
            }
        } else {
            if ($name) {
                $this->assign('name', $name);
            } else {
                $data = ['err' => 'id参数错误'];
            }
            $data = $this->fetch();
        }
        return $data;
    }
    public function shenheAllRecycle()
    {
        $admin = session('admin', '', 'mmjtAdmin');

        $admin = Db::name('admin')->find($admin['id']);

        if ($admin['type'] != 1) {
            return ['err' => '无权限'];
        }
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            $current_time = time();
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $inserts = [];
                $updateUids = [];
                $upids = [];
                $names = Db::name('recycle_review')->where(['user_id'=>['in',$post], 'state'=>0])->column('*', 'user_id');
                $users = Db::name('user')->where(['id'=>['in',array_keys($names)]])->column('*', 'id');
                foreach ($post as $k => $v) {
                    if ($type == 1) {
                        $inserts[] = [
                            'channel' => 1,
                            'user_id' => $v,
                            'phone' => $users[$v]['phone'],
                            'data' => json_encode($users[$v]),
                            'ip' => $names[$v]['ip'],
                            'os' => $names[$v]['os'],
                            'create_time' => $current_time,
                        ];
                        $updateUids[] = $v;
                    }
                    $upids[] = $names[$v]['id'];
                }
                Db::startTrans();
                try {
                    if ($inserts) {
                        Db::name('recycle_user')->insertAll($inserts);
                        Db::name('user')->where(['id'=>['in', $updateUids]])->update([
                                //'name' => '已注销',
                                //'phone'=>null,
                                'wechat'=>null,
                                'qq_openID'=>null,
                                'device_id'=>null,
                                'delete_time' => $current_time
                            ]);
                    }
                    Db::name('recycle_review')->where(['id'=>['in', $upids]])->update([
                            'state'=>$type,
                            'admin_id'=>$admin['id'],
                            'update_time' => $current_time
                        ]);
                    $res = true;
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    $res = false;
                    // 回滚事务
                    Db::rollback();
                    return ['err' => $e->getMessage()];
                }
                if ($res) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }
    public function userlog()
    {
        $where = [];

        $type = input('type');

        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            // if ($search_type == 'user_id') {
            //     $where[$search_type] = $search_name;
            // } else {
            //     $where[$search_type] = ['like', '%' . $search_name . '%'];
            // }
             $where[$search_type] = $search_name;
        }
        
        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $where['time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['time'] = ['elt', strtotime($end)];
        }
        

        $data = Db::name('user_request_log')
            ->where($where)
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('start', $start);
        $this->assign('end', $end);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }




    // 提现限制
    public function tixianlimit()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                UserPunish::inc($user['id'], 'withdraw_limit');
                $tixianlimit = Db::name('withdraw_limit')->where(['user_id'=>$post['user_id']])->find();
                if($tixianlimit){
                    $result = ['state' => 0, 'msg' => '已设置限制'];
                }else{
                    $tixianlimitid = Db::name('withdraw_limit')->insertGetid(['user_id'=>$post['user_id'],'reason'=>$post['reason'], 'time' => $time, 'admin_id'=>$this->adminInfo['id']]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('withdraw_limit')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

            $dataList = $data->all();

            $admin = Db::name('admin')->column('name','id');
            foreach ($dataList as &$value) {
                $value['admin_name'] = $admin[$value['admin_id']] ?? '';
            }
            
            $this->assign('data', $dataList);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function untixianlimit()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('withdraw_limit')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }



    // 敏感行为监听
    public function warn()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                UserPunish::inc($user['id'], 'warn_monitor');
                $warnlimit = Db::name('user_warn')->where(['user_id'=>$post['user_id']])->find();
                if($warnlimit){
                    $result = ['state' => 0, 'msg' => '已设置监听'];
                }else{
                    $warnlimitid = Db::name('user_warn')->insertGetid(['user_id'=>$post['user_id'], 'time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('user_warn')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function unwarn()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('user_warn')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }

    public function warnRecords()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where['t2.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('user_warn_records')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }





    // 修改年龄限制
    public function changeAgeLimit()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                UserPunish::inc($user['id'], 'age_limit');
                $changeAgeLimit = Db::name('change_age_limit')->where(['user_id'=>$post['user_id']])->find();
                if($changeAgeLimit){
                    $result = ['state' => 0, 'msg' => '已设置限制'];
                }else{
                    $changeAgeLimitid = Db::name('change_age_limit')->insertGetid(['user_id'=>$post['user_id'], 'time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('change_age_limit')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function unchangeAgeLimit()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('change_age_limit')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }

    public function dovetail()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user_repeat_check = Db::name('user_repeat_check')->where(['user_id'=>$post['user_id']])->find();
            $binduser = Db::name('user_repeat_check')->where(['user_id'=>$post['value']])->find();

            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user_repeat_check) {
                $custom = $user_repeat_check['custom'] ? explode(',', $user_repeat_check['custom']) : [];
                if(in_array($post['value'], $custom)){
                    return ['state' => 0, 'msg' => '重复绑定'];
                }else{
                    $custom[] = $post['value'];
                    Db::name('user_repeat_check')->where(['user_id'=>$user_repeat_check['user_id']])->update(['custom'=>implode(',', $custom)]);


                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }else{
                Db::name('user_repeat_check')->insert(['user_id'=>$post['user_id'], 'custom'=>$post['value']]);
                $result = ['state' => 1, 'msg' => '操作成功'];
            }
            if($binduser){
                $custom = $binduser['custom'] ? explode(',', $binduser['custom']) : [];
                $custom[] = $post['user_id'];
                Db::name('user_repeat_check')->where(['user_id'=>$binduser['user_id']])->update(['custom'=>implode(',', $custom)]);
            }else{
                Db::name('user_repeat_check')->insert(['user_id'=>$post['value'], 'custom'=>$post['user_id']]);
            }
            return $result;
        }
    }
    public function dovetaildel($uid, $touid)
    {
        $user_repeat_check = Db::name('user_repeat_check')->where(['user_id'=>$uid])->find();
        $binduser = Db::name('user_repeat_check')->where(['user_id'=>$touid])->find();

        if($user_repeat_check['custom']){
            $custom = explode(',', $user_repeat_check['custom']);
            $custom = delByValue($custom, $touid);
            Db::name('user_repeat_check')->where(['user_id'=>$user_repeat_check['user_id']])->update(['custom'=>implode(',', $custom)]);
        }
        if($binduser['custom']){
            $custom = explode(',', $binduser['custom']);
            $custom = delByValue($custom, $uid);
            Db::name('user_repeat_check')->where(['user_id'=>$binduser['user_id']])->update(['custom'=>implode(',', $custom)]);
        }

        return ['state' => 1, 'msg' => '设置成功'];
    }

    public function addauthpic()
    {
        if (request()->isAjax()) {

            $post = input('');

            if (!isset($post['masterimg']) || !$post['masterimg']) {
                return ['err' => '至少需上传一张图片'];
            }

            $user_repeat_check = Db::name('user_repeat_check')->where(['user_id'=>$post['id']])->find();
            if (!$user_repeat_check) {
                Db::name('user_repeat_check')->insert([
                    'user_id' => $post['id']
                ]);
                $idcards = '';
            } else {
                $idcards = $user_repeat_check['idcards'];
            }

            $idcards = $idcards ? $idcards . ',' . $post['masterimg'] : $post['masterimg'];

            $result = Db::name('user_repeat_check')->where(['user_id' => $post['id']])->update(['idcards'=>$idcards]);

            if ($result) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function clearaccount($id, $type = 0)
    {
        if ($type == 1) {
            $result = Db::name('user')->where(['id'=>$id])->update(['wechat' => null, 'wechat_name'=>'']);
            Db::name('wechat_union')->where(['user_id'=>$id])->delete();
        } else {
            $result = Db::name('user')->where(['id'=>$id])->update(['zhifuname' => '', 'zhifucount' => '']);
        }

        if ($result) {
            $data = ['ret' => '清空成功'];
        } else {
            $data = ['err' => '清空失败'];
        }
        return $data;
    }

    public function setRealAvatar($id, $state)
    {
        $result = Db::name('user')->where(['id'=>$id])->update(['real_avatar'=>$state]);

        if ($result) {
            Db::name('user_img')->where(['user_id'=>$id, 'is_avatar'=>1])->update(['is_face'=>$state]);
            $data = ['ret' => '设置成功'];
        } else {
            $data = ['err' => '设置失败'];
        }
        return $data;
    }

    public function setRealFace($id, $state)
    {
        $result = Db::name('user_img')->where(['id'=>$id])->update(['is_face'=>$state]);

        if ($result) {
            $data = ['ret' => '设置成功'];
        } else {
            $data = ['err' => '设置失败'];
        }
        return $data;
    }



    // 修改年龄限制
    public function SearchLimit()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                UserPunish::inc($user['id'], 'search_limit');
                $SearchLimit = Db::name('search_limit')->where(['user_id'=>$post['user_id']])->find();
                if($SearchLimit){
                    $result = ['state' => 0, 'msg' => '已设置限制'];
                }else{
                    $SearchLimitid = Db::name('search_limit')->insertGetid(['user_id'=>$post['user_id'], 'time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('search_limit')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function unSearchLimit()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('search_limit')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }




    public function userSlogan()
    {
        $where = [];

        $order = 'id desc';
        $where['delete_time'] = 0;
        $where['reg'] = 1;

        $data = Db::name('user')->where($where)->where("slogan <> '' || self_slogan <> ''")->order($order)->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function($item, $key){
            return $item;
        });

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function clearSlogan($id, $key = 0)
    {
        if ($key == 0) {
            $update['slogan'] = '';
        } else if ($key == 1) {
            $update['self_slogan'] = '';
        } else {
            $update['slogan'] = '';
            $update['self_slogan'] = '';
        }
        $user = Db::name('user')->where(['id'=>$id])->update($update);
        if ($user) {
            return ['ret' => '设置成功'];
        }
        return ['err' => '设置失败'];
    }



    // 邀请奖励限制
    public function invitelimit()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                $invitelimit = Db::name('limit_invite')->where(['user_id'=>$post['user_id']])->find();
                if($invitelimit){
                    $result = ['state' => 0, 'msg' => '已设置限制'];
                }else{
                    $invitelimitid = Db::name('limit_invite')->insertGetid(['user_id'=>$post['user_id'],'reason'=>$post['reason'], 'time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('limit_invite')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function uninvitelimit()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('limit_invite')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }
    public function addBlacklist()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$post['auid'] || !$post['buid']) {
                return ['err' => '用户ID不能为空'];
            }
            if ($post['auid'] == $post['buid']) {
                return ['err' => '用户ID不能相同'];
            }
            $inserts = [];
            if ($post['type'] == 1) {
                $inserts[] = [
                    'user_id'   =>  $post['auid'],
                    'to_user'   =>  $post['buid']
                ];
                $inserts[] = [
                    'user_id'   =>  $post['buid'],
                    'to_user'   =>  $post['auid']
                ];
            } else if ($post['type'] == 2) {
                $inserts[] = [
                    'user_id'   =>  $post['auid'],
                    'to_user'   =>  $post['buid']
                ];
            } else if ($post['type'] == 3) {
                $inserts[] = [
                    'user_id'   =>  $post['buid'],
                    'to_user'   =>  $post['auid']
                ];
            }
            $db = false;
            if ($inserts) {
                $db = Db::name('blacklist')->insertAll($inserts);
            }
            if ($db) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function refreshLoginTIme($id, $t = 0)
    {
        if ($t) {
            $res = Db::name('user')->where(['id'=>$id])->setInc('last_login_time', $t);
        } else {
            $res = Db::name('user')->where(['id'=>$id])->update(['last_login_time'=>time()]);
        }
        if ($res) {
            $data = ['ret' => '操作成功'];
        } else {
            $data = ['err' => '操作失败'];
        }
        return $data;
    }


    public function authlist()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where['t2.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.create_time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('auth')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name,t2.sex')->order('t1.create_time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }



    // 修改年龄限制
    public function ChatSingle()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                // UserPunish::inc($user['id'], 'privatechat_user_single');
                $ChatSingle = Db::name('privatechat_user_single')->where(['user_id'=>$post['user_id']])->find();
                if($ChatSingle){
                    $result = ['state' => 0, 'msg' => '已设置限制'];
                }else{
                    $ChatSingleid = Db::name('privatechat_user_single')->insertGetid(['user_id'=>$post['user_id'], 'reason'=>$post['reason'], 'time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('privatechat_user_single')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function unChatSingle()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('privatechat_user_single')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }

    // 修改收费价格限制
    public function ChatPriceSet()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                // UserPunish::inc($user['id'], 'privatechat_user_single');
                $ChatPriceSet = Db::name('limit_change_price_config')->where(['user_id'=>$post['user_id']])->find();
                if($ChatPriceSet){
                    $result = ['state' => 0, 'msg' => '已设置限制'];
                }else{
                    $ChatPriceSetid = Db::name('limit_change_price_config')->insertGetid(['user_id'=>$post['user_id'], 'reason'=>$post['reason'], 'time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('limit_change_price_config')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function unChatPriceSet()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('limit_change_price_config')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }


    public function warnuser()
    {
        $where = [];
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where['t2.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('warn_user_records')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name,t2.is_banned')->order('t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addwarnuser()
    {
        $post = input('post.');

        $user = Db::name('user')->find($post['user_id']);

        $time = time();
        $result = ['state' => 0, 'msg' => '操作失败'];
        if ($user) {
            $warn_user_records = Db::name('warn_user_records')->where(['user_id'=>$post['user_id']])->find();
            if($warn_user_records){
                $result = ['state' => 0, 'msg' => '已存在列表'];
            }else{
                $warn_user_recordsid = Db::name('warn_user_records')->insertGetid(['user_id'=>$post['user_id'], 'function'=>$post['reason'], 'time' => $time]);
                $result = ['state' => 1, 'msg' => '操作成功'];
            }
        }
        return $result;
    }
    
    public function unwarnuser()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('warn_user_records')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }



    public function warnuserchat()
    {
        $where = [];
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where['t2.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('warn_user_chat_records')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name,t2.is_banned')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }


    public function selectUsers()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                if ($user['sex'] == '男') return ['state' => 0, 'msg' => '当前仅支持女号'];
                $selectUsers = Db::name('select_users')->where(['user_id'=>$post['user_id']])->find();
                if($selectUsers){
                    $result = ['state' => 0, 'msg' => '已添加'];
                }else{
                    $selectUsersid = Db::name('select_users')->insertGetid(['user_id'=>$post['user_id'], 'time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);

            $data = Db::name('select_users')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function unselectUsers()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('select_users')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }

    public function risk()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $user = Db::name('user')->find($post['user_id']);

            $time = time();
            $result = ['state' => 0, 'msg' => '操作失败'];
            if ($user) {
                $risk = Db::name('user_risk')->master()->where(['user_id'=>$post['user_id'], 'end_time'=>0])->find();
                if($risk){
                    $result = ['state' => 0, 'msg' => '已添加'];
                }else{
                    $selectUsersid = Db::name('user_risk')->insertGetid(['user_id'=>$post['user_id'], 'reason'=>$post['reason'], 'create_time' => $time]);
                    $result = ['state' => 1, 'msg' => '操作成功'];
                }
            }
            return $result;
        }else{
            $over = input('over', 0);
            $where = [];

            $search_name = input('param.name');
            $search_type = input('param.search');
            if ($search_name && $search_type) {
                if(in_array($search_type, ['id', 'phone'])){
                    $where['t2.'.$search_type] = $search_name;
                }elseif(in_array($search_type, ['name'])){
                    $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
                }else{
                    $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
                }
            }

            $start = input('start');
            $end = input('end');

            if ($start && $end) {
                $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
            } else if ($start && !$end) {
                $where['t1.create_time'] = ['egt', strtotime($start)];
            } else if (!$start && $end) {
                $where['t1.create_time'] = ['elt', strtotime($end)];
            }
            $this->assign('start', $start);
            $this->assign('end', $end);
            $this->assign('over', $over);

            if ($over==2) {
                $where['end_time'] = ['>', 0];
            } else {
                $where['t1.level'] = $over+1;
                $where['end_time'] = 0;
            }

            $orders = ['t1.create_time desc', 't1.update_time desc', 't1.end_time desc'];

            $data = Db::name('user_risk')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name,t2.is_banned')->order($orders[$over])->paginate(5, false, ['query' => request()->param()])->each(function($item){
                    $item['data'] = $item['data'] ? json_decode($item['data'], true) : [];
                    $item['datalastest'] = sizeof($item['data']) ? $item['data'][sizeof($item['data']) - 1]['v'] : '';
                    $item['update_time'] = sizeof($item['data']) ? $item['data'][sizeof($item['data']) - 1]['t'] : 0;
                    return $item;
                });

            
            $this->assign('data', $data);
            $page = $data->render();
            $this->assign('page', $page);
            return $this->fetch();
        }
    }

    public function delRisk()
    {
        $id = input('id');
        $level = input('level/d', 0);
        
        if (request()->isAjax()) {
            if ($level) {
                $name = Db::name('user_risk')->find($id);
                if($name){
                    $admin = Session::get('admin', 'mmjtAdmin');
                    $name['data'] = $name['data'] ? json_decode($name['data'], true) : [];
                    array_push($name['data'], ['admin_id'=>$admin['id'], 'admin_name'=>$admin['name'], 't'=>time(), 'v'=>'调整风控级别：正常 => 低度']);
                    Db::name('user_risk')->where('id', $id)->update(['level'=>$level,'data'=> json_encode($name['data'], JSON_UNESCAPED_UNICODE), 'update_time'=>time()]);
                }
            } else {
                Db::name('user_risk')->where('id', $id)->update(['end_time'=>time()]);
            }
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }

    public function dealRisk()
    {
        $admin = Session::get('admin', 'mmjtAdmin');
        $id = input('id');
        $name = Db::name('user_risk')->find($id);
        if($name){
            $name['data'] = $name['data'] ? json_decode($name['data'], true) : [];
            foreach ($name['data'] as $key => $value) {
                $name['data'][$key]['images'] = isset($value['imgs']) && $value['imgs'] ? explode(',', $value['imgs']) : [];
            }
        }else{
            return ["err" => '举报不存在'];
        }
        if (request()->isAjax()) {
            $remark = input('post.remark');
            $reason = input('post.reason');
            if(!$remark) {
                return ["err" => '请填写处理描述'];
            }
            $images = input('post.masterimg');
            if ($name['reason']!=$reason) {
                array_push($name['data'], ['admin_id'=>$admin['id'], 'admin_name'=>$admin['name'], 't'=>time(), 'v'=>'原因修改：'.$name['reason'] . ' => ' . $reason]);
            }
            array_push($name['data'], ['admin_id'=>$admin['id'], 'admin_name'=>$admin['name'], 't'=>time(), 'v'=>$remark, 'imgs'=>$images]);

            $update = ['reason'=>$reason, 'data'=>json_encode($name['data'], JSON_UNESCAPED_UNICODE)];

            $db = Db::name('user_risk')->where(['id'=>$name['id']])->update($update);

            if ($db) {
                $data = ['ret' => '修改成功'];
            } else {
                $data = ['err' => '修改失败'];
            }
        }else{
            $read = input('read', 0);
            $this->assign('read', $read);
            
            $this->assign('name', $name);
            $data = $this->fetch();
        }
        return $data;
    }


    public function deedLimit()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }


        $data = db('user_deed_limit')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addDeedLimit()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');
            $day = intval($post['expire_day'] ?? 0);
            if (!$day) {
                return ['err' => '请输入天数'];
            }
            $timenow = time();
            $post['create_time'] = $timenow;
            $post['expire_time'] = $timenow + $day * 86400;

            $res = db('user_deed_limit')->insert($post);

            $ops = [
                ['', ''],
                ['发布涉黄作品', '发布作品'],
                ['发布涉黄评论', '发表评论'],
                ['设置低俗昵称', '修改昵称'],
            ];

            $content = "由于你多次".$ops[$post['type']][0]."，平台限制".$day."天内不得".$ops[$post['type']][1];
            if ($res) {
                Privatechat::notice($post['user_id'], $content);
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            if ($id) {
                $name = db('user_deed_limit')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function rmDeedLimit()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('user_deed_limit')->where(['id'=>$pid, 'update_time'=>0])->update(['update_time'=>time()]);
                if ($res) {
                    $data = ['ret' => '解除成功'];
                } else {
                    $data = ['err' => '解除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function chatPriceRecords()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where['t2.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('user_chat_price_records')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.user_id desc, t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item) use ($where)
        {
            return $item;
        });

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function exceptions()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['user_id'])){
                $where[$search_type] = $search_name;
            }
        }

        $data = Db::name('user_exception')->where($where)->field('*')->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $list = $data->all();
        $users = Db::name('user')->where(['id'=>['in',array_column($list,'user_id')]])->column('yqr,realname_auth', 'id');
        $yqrs = Db::name('user')->where(['yqm'=>['in', array_column($users, 'yqr')]])->column('id,name,sex,age', 'yqm');
        foreach ($list as $k => $v) {
            $list[$k]['yqr'] = false;
            $list[$k]['realname_auth'] = 1;
            if (isset($users[$v['user_id']])) {
                $list[$k]['realname_auth'] = $users[$v['user_id']]['realname_auth'];
                if ($users[$v['user_id']]['yqr'] && isset($yqrs[$users[$v['user_id']]['yqr']])) {
                    $list[$k]['yqr'] = $yqrs[$users[$v['user_id']]['yqr']];
                }
            }
        }
        $this->assign('data', $list);

        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function scoreToVolley()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where[$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where[$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where[$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('wallet_to_volley')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $dataList = $data->all();
        $user = Db::name('user')->where(['id'=>['in', array_column($dataList, 'user_id')]])->column('name', 'id');
        foreach ($dataList as &$value) {
            $value['name'] = $user[$value['user_id']] ?? '';
        }

        $this->assign('data', $dataList);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }


    public function LimitDating()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');

        if ($search_name && $search_type) {
            $where[$search_type] = $search_name;
        }


        $data = db('limit_dating')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $dataList = $data->all();
        $users = Db::name('user')->where(['id'=>['in', array_column($dataList, 'user_id')]])->column('last_login_datetime', 'id');
        $userData = Db::name('user_data')->where(['user_id'=>['in', array_column($dataList, 'user_id')]])->column('topup', 'user_id');
        $userTopupLimit = Db::name('topup_limit')->where(['user_id'=>['in', array_column($dataList, 'user_id')]])->column('value', 'user_id');

        $config = Config::index('topup');
        foreach ($dataList as &$value) {
            $value['last_login_datetime'] = $users[$value['user_id']]??'';
            $value['topup'] = $userData[$value['user_id']]??0;
            if (isset($userTopupLimit[$value['user_id']])) {
                $value['topup_limit'] = $userTopupLimit[$value['user_id']];
            } else {
                $value['topup_limit'] = $this->rechargeLimitTempUp($userData[$value['user_id']]??0, $config['topup_max']);
            }
        }

        $this->assign('data', $dataList);
        $this->assign('page', $page);

        return $this->fetch();
    }
    public function rechargeLimitTempUp($rechargecount, $topup_max)
    {
        $userTempQuota = 0;
        $userlimit = 0;
        if($rechargecount < 3000){
            $userTempQuota = 50;
        } else if($rechargecount < 5000){
            $userTempQuota = 30;
        } else if($rechargecount < 10000){
            $userTempQuota = 20;
        } else if($rechargecount < 20000){
            $userTempQuota = 10;
        }

        if($rechargecount >= 30000){
            $userlimit = 20 + $userTempQuota;
        } else if($rechargecount >= 27000){
            $userlimit = 40 + $userTempQuota;
        } else if($rechargecount >= 23000){
            $userlimit = 60 + $userTempQuota;
        } else if($rechargecount >= 20000){
            $userlimit = 80 + $userTempQuota;
        } else if($rechargecount >= 15000){
            $userlimit = 100 + $userTempQuota;
        } else if($rechargecount >= 10000){
            $userlimit = 200 + $userTempQuota;
        } else if($rechargecount >= 5000){
            $userlimit = 400 + $userTempQuota;
        } else {
            $userlimit = $topup_max + $userTempQuota;
        }

        return $userlimit;
    }

    public function addLimitDating()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $post['time'] = time();

            if (!$post['user_id']) return ['err'=>'用户id必填'];

            $exist = db('limit_dating')->master()->where(['user_id'=>$post['user_id']])->find();
            if ($exist) return ['err'=>'已存在限制'];

            $res = db('limit_dating')->insert($post);
            if ($res) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $user_id = input('user_id/d', '');
            $this->assign('user_id', $user_id);
            $data = $this->fetch();
        }
        return $data;
    }

    public function rmLimitDating()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('limit_dating')->where(['id'=>$pid])->delete();
                if ($res) {
                    $data = ['ret' => '解除成功'];
                } else {
                    $data = ['err' => '解除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function parentlist()
    {
        $currentUserId = input('id/d', 0);
        $i = 10;
        $user = Db::name('user')->find($currentUserId);

        $chain = [$user];
        if ($user) {
            while ($currentUserId && $i) {
                if ($user['yqr']) {
                    $user = Db::name('user')->where(['yqm'=>$user['yqr']])->find();
                    if ($user) {
                        if (in_array($user['id'], array_column($chain, 'id'))) break;
                        $chain[] = $user;
                        $currentUserId = $user['id'];
                    } else {
                        $currentUserId = 0;
                    }
                }
                $i--;
            }
        }

        foreach ($chain as &$value) {
            $value['level_text'] = $this->userLevels[$value['level']] ?? '异常';
        }

        $this->assign('data', $chain);

        return $this->fetch();
    }


    public function levelSet()
    {
        $id = input('id/d', 0);
        $user = Db::name('user')->find($id);

        if (request()->isAjax()) {
            $level = input('level/d', 0);
            $level_lock = input('level_lock/d', 0);

            $res = UserLevel::change($id, $level, false, $level_lock);
            if ($res) {
                return ['ret' => '操作成功'];
            }

            return ['err' => '操作失败'];
        } else {

            $this->assign('level', $this->userLevels);
            $this->assign('user', $user);
            return $this->fetch();
        }
    }


    public function levelRecords()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where['t2.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('user_level_records')->alias('t1')->join('user t2','t1.user_id=t2.id')->where($where)->field('t1.*,t2.name')->order('t1.time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $dataList = $data->all();

        $level = ['普通会员','超级会员','运营商','合伙人'];
        $lock = ['否','是'];
        $admin = Db::name('admin')->column('name','id');
        foreach ($dataList as &$value) {
            $value['admin_name'] = $admin[$value['admin_id']] ?? '';

            $origin_level_text = $level[$value['origin_level']]??'';
            $level_text = $level[$value['level']]??'';
            $value['level_text'] = $value['origin_level'] == $value['level'] ? '' : $origin_level_text . ' => ' . $level_text;

            $origin_lock_text = $lock[$value['origin_lock']]??'';
            $lock_text = $lock[$value['lock']]??'';
            $value['lock_text'] = $value['origin_lock'] == $value['lock'] ? '' : $origin_lock_text . ' => ' . $lock_text;
        }
        
        $this->assign('data', $dataList);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function setKefu()
    {
        $user_id = input('user_id/d', 0);

        $user = Db::name('user')->find($user_id);
        if (!$user) return ['err'=>'用户不存在'];
        if (!$user['password']) return ['err'=>'当前用户未设置登录密码'];

        $admin = Db::name('admin')->where(['bind_uid'=>$user_id])->find();
        if ($admin) return ['err'=>'已设置为客服'];

        $res = Db::name('admin')->insert([
            'type'=>2,
            'name'=>$user['phone'],
            'password'=>md5($user['password']),
            'bind_uid'=>$user_id,
            'hide'=>1,
            'create_time'=>time()
        ]);
        return $res ? ['ret'=>'设置成功'] : ['err'=>'设置失败'];
    }

    public function tixianFenzhang()
    {
        $where = ['withdraw_no'=>input('order_no/s', '')];

        //$data = Db::name('withdraw_recharge_mapping')->where($where)->field('*')->order('id desc')->select();
        $data = Db::name('withdraw_recharge_mapping')->where($where)->field('*')->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();
        $txno=input('order_no/s');
        $txuser=Db::name('withdraw')->where('order_no',$txno)->field('id,userid')->order('id','desc')->find();
        $userid=$txuser['userid'];
        $user=Db::name('user')->where('id',$userid)->field('id,name')->find();
        $username=$user['name'];
        $this->assign('userid',$userid);
        $this->assign('username',$username);
        // 单独计算mapping_amount分账总和（使用聚合函数）
        $totalAmount = Db::name('withdraw_recharge_mapping')
            ->where($where)
            ->sum('mapping_amount');
        // 将总和添加到分页数据中
        $this->assign('total_amount',$totalAmount);
        $this->assign('txnoid',$txuser['id']);
        $this->assign('txno',$txno);
        $this->assign('page', $page);
        $this->assign('data', $data);

        return $this->fetch();
    }
}
